package cn.huiyunche.base.service.interfaces.impl;import cn.huiyunche.base.service.constant.App;import cn.huiyunche.base.service.constant.BVehicleConstant;import cn.huiyunche.base.service.constant.QiniuConstant;import cn.huiyunche.base.service.constant.TmsUrlConstant;import cn.huiyunche.base.service.enums.*;import cn.huiyunche.base.service.form.*;import cn.huiyunche.base.service.framework.redis.MindsJedisConnectionFactory;import cn.huiyunche.base.service.framework.utils.HYCUtils;import cn.huiyunche.base.service.framework.utils.QiniuUtils;import cn.huiyunche.base.service.interfaces.*;import cn.huiyunche.base.service.mappers.*;import cn.huiyunche.base.service.mappers.ext.OrderViewMapper;import cn.huiyunche.base.service.mappers.ext.SOrderViewMapper;import cn.huiyunche.base.service.model.*;import cn.huiyunche.base.service.model.SOrderExample.Criteria;import cn.huiyunche.base.service.utils.UniquenessFlagUnits;import cn.huiyunche.base.service.vo.*;import cn.huiyunche.tools.basic.exceptions.BusinessException;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONArray;import org.apache.commons.collections4.CollectionUtils;import org.apache.commons.lang3.StringUtils;import org.joda.time.DateTime;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.BeanUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import redis.clients.jedis.Jedis;import java.math.BigDecimal;import java.math.RoundingMode;import java.text.SimpleDateFormat;import java.util.*;import java.util.stream.Collectors;/** * @ClassName: ShipServiceImpl * @Description: 客户订单接口实现 * @author: Aaron * @date: 2016年5月10日 下午12:39:32 */@Servicepublic class SOrderServiceImpl implements SOrderService {    private static final Logger LOGGER = LoggerFactory.getLogger(SOrderServiceImpl.class);    //省市县连接符    private static final String CONTACT_SYMBOL = "-";    @Autowired    private SOrderMapper sOrderMapper;    @Autowired    private OrderViewMapper orderViewMapper;    @Autowired    private SOrderDetailMapper orderDetailMapper;    @Autowired    private SOrderDetailService sOrderDetailService;    @Autowired    private SUserVehiclesMapper userVehiclesMapper;    @Autowired    private SUserAddrMapper userAddressMapper;    @Autowired    private UserService userService;    @Autowired    private SOrderVinMapper vinMapper;    @Autowired    private MindsJedisConnectionFactory connectionFactory;    @Autowired    private GDMapService mapService;    @Autowired    private OrderStatusLogService orderStatusLogService;    @Autowired    private BVehicleBrandMapper brandMapper;    @Autowired    private BVehicleMapper vehicleMapper;    @Autowired    private CWaybillMapper cWaybillMapper;    @Autowired    private PushService pushService;    @Autowired    private SOrderDiscountMapper sOrderDiscountMapper;    @Autowired    private SServiceOrderService sServiceOrderService;    @Autowired    private SOrderProductService sOrderProductService;    @Autowired    private SServiceOrderVehicleService sServiceOrderVehicleService;    @Autowired    private SOrderVinService sOrderVinService;    @Autowired    private SServiceOrderStatusLogService sServiceOrderStatusLogService;    @Autowired    private SOrderFeeDetailService sOrderFeeDetailService;    @Autowired    private SOrderStatusLogMapper sOrderStatusLogMapper = null;    @Autowired    private CWaybillAttachMapper cWaybillAttachMapper = null;    @Autowired    private SOrderViewMapper sOrderViewMapper;    @Autowired    private CWaybillTrailService cWaybillTrailService;    @Autowired    private CWaybillDetailMapper cWaybillDetailMapper;    @Autowired    private SServiceOrderStatusLogMapper sServiceOrderStatusLogMapper;    @Autowired    private SOrderVinMapper sOrderVinMapper = null;    @Autowired    private SOrderDetailMapper sOrderDetailMapper = null;    @Autowired    private SOrderFeedetailMapper sOrderFeedetailMapper = null;    @Autowired    private CWaybillDetailService cWaybillDetailService;    @Autowired    private BActivityService bActivityService;    @Autowired    private FeesService feesService;    @Autowired    private BVehicleClassService bVehicleClassService;    @Autowired    private BAreaService bAreaService;    @Autowired    private BProductsService productsService;    @Autowired    private SOrderStowageService sOrderStowageService;    // @Autowired    // private SOrderImportedStowageService sOrderImportedStowageService;    @Autowired    private BStowageVehicleService bStowageVehicleService;    @Autowired    private BCompanyUserService bCompanyUserService;    @Autowired    private SOrderTrailerService sOrderTrailerService;    @Autowired    private SServiceOrderFeedetailService sServiceOrderFeedetailService;    @Autowired    private BDistanceBetweenAddressesService bDistanceBetweenAddressesService;    @Autowired    private CWaybillAttachService cWaybillAttachService;    @Autowired    private SOrderPayRoleService sOrderPayRoleService = null;    private SOrderPayRoleService getSOrderPayRoleService() {        return this.sOrderPayRoleService;    }    private SOrderFeedetailMapper getSOrderFeedetailMapper() {        return this.sOrderFeedetailMapper;    }    private SOrderDetailMapper getSOrderDetailMapper() {        return this.sOrderDetailMapper;    }    private SOrderVinMapper getSOrderVinMapper() {        return this.sOrderVinMapper;    }    private CWaybillMapper getCWaybillMapper() {        return this.cWaybillMapper;    }    private SOrderStatusLogMapper getSOrderStatusLogMapper() {        return this.sOrderStatusLogMapper;    }    @Override    public SOrder selectByPrimaryKey(long orderId) {        return sOrderMapper.selectByPrimaryKey(orderId);    }    @Override    public List<SOrder> selectByExample(SOrderExample example) {        return sOrderMapper.selectByExample(example);    }    @Autowired    private UserAddressService userAddressService;    @Autowired    private SendMessageService sendMessageService;    @Autowired    private CodeService codeService;    @Autowired    private CWaybillContactsService cWaybillContactsService;    @Override    @Deprecated    public Map<String, Object> add(OrderByExcelVo excelVo, Boolean isPublish) throws Exception {        LOGGER.info("SalesOrderServiceImpl.create params : {}", excelVo);        Map<String, Object> map = new HashMap<String, Object>();        SOrder order = new SOrder();//      BeanCopier beanCopierT = BeanCopier.create(OrderByExcelVo.class, SOrder.class, false);        BeanUtils.copyProperties(excelVo, order);        Long userId = userService.getCurrentUserVo().getId();        Integer userType = userService.getCurrentUserVo().getType();        order.setUserId(userId);        order.setOrderCode(UniquenessFlagUnits.generateUniquenessFlag("CO"));        order.setOrderType(userType);        // 添加isUrgent modify by [Tuffy] 何东阳        // order.setIsUrgent(AvailableEnum.F.getValue());        order.setOrderCost(BigDecimal.ZERO.setScale(2));        //保存状态、未付款状态        order.setStatus(COrderStatusEnum.SAVED.getValue());        order.setPayStatus(PaymentStatusEnum.UNPAID.getValue());        //查询运距        order.setDistance(                mapService.distance(order.getDepartCountyCode(), new StringBuilder(order.getDepartProvinceName()).append(order.getDepartCityName()).toString(), order.getReceiptCountyCode(),                        new StringBuilder(order.getReceiptProvinceName()).append(order.getReceiptCityName()).toString()));        // 计算车辆总数        int amount = 0;        List<VehiclesBrandVo> vehiclesBrandList = JSONArray.parseArray(excelVo.getVehiclesbrands(), VehiclesBrandVo.class);        for (VehiclesBrandVo vbv : vehiclesBrandList) {            amount += vbv.getVehiclecount();        }        order.setAmount(amount);        // 保存订单        sOrderMapper.insertSelective(order);        //保存客户订单和物流产品关联信息        sOrderProductService.add(order.getId(), excelVo.getProductId(), order.getArriveDate());        long orderId = order.getId();        map.put("id", orderId);        map.put("ordercode", order.getOrderCode());        LOGGER.info("SalesOrderServiceImpl.create insertSelective return : {}", orderId);        // 保存订单流转状态变更        orderStatusLogService.insertSelective(orderId, StatusCategoryEnum.PROCESS, COrderStatusEnum.SAVED, false, null);        // 保存订单车辆信息        this.buildVehicles(vehiclesBrandList, order.getId(), order.getEstValue().divide(BigDecimal.valueOf(order.getAmount()), 0, RoundingMode.UP));        // 保存用户常用车辆        //企业批量下单不保存常用车型//      this.addUserVehicles(userId, vehiclesBrandList);        // 计算订单费用        Map<String, Object> feesMap = this.computeFees(orderId, order.getIsPick(), order.getIsDeliv(), excelVo.getProductId(), true);        map.putAll(feesMap);        if (isPublish) {            //发布状态            this.publish(order.getId(), false);        }        return map;    }    @Override    public Map<String, Object> addByExcel(SOrderImportedVo soiv) throws Exception {        LOGGER.info("SalesOrderServiceImpl.create params : {}", soiv);        Map<String, Object> map = new HashMap<String, Object>();        SOrder order = new SOrder();        long userId = userService.getCurrentUserVo().getId();        Integer userType = userService.getCurrentUserVo().getType();        order.setUserId(userId);        order.setOrderCode(UniquenessFlagUnits.generateUniquenessFlag("CO"));        order.setIsPick(soiv.getIsPick());        order.setIsDeliv(soiv.getIsDeliv());        order.setDeliveryDate(soiv.getDeliveryDate());        order.setDeliveryTime(soiv.getDeliveryTime());        order.setArriveDate(soiv.getArriveDate());        order.setIsSencondhand(soiv.getIsSencondhand());        order.setIsMobile(soiv.getIsMobile());        order.setEstValue(soiv.getEstValue());        order.setOrderType(userType);        // 地址赋值        this.reSetAddressInOrderByExcel(order, soiv, true);        this.reSetAddressInOrderByExcel(order, soiv, false);        // 保存状态、未付款状态        order.setStatus(COrderStatusEnum.SAVED.getValue());        order.setPayStatus(PaymentStatusEnum.UNPAID.getValue());        // 计算运距        // SUserAddr depa =        // userAddressMapper.selectByPrimaryKey(form.getDepartaddrid());        // SUserAddr rece =        // userAddressMapper.selectByPrimaryKey(form.getReceiptaddrid());        order.setDistance(mapService.distance(order.getDepartCountyCode(),                new StringBuilder(order.getDepartProvinceName()).append(order.getDepartCityName()).append(order.getDepartCountyName()).toString(),                order.getReceiptCountyCode(), new StringBuilder(order.getReceiptProvinceName()).append(order.getReceiptCityName()).append(order.getReceiptCountyName()).toString()));        // 计算车辆总数        int amount = 0;        List<VehiclesBrandVo> vehiclesBrandList = JSONArray.parseArray(this.buildOrderVehicleByExcel(soiv), VehiclesBrandVo.class);        for (VehiclesBrandVo vbv : vehiclesBrandList) {            amount += vbv.getVehiclecount();        }        order.setAmount(amount);        // 保存订单        sOrderMapper.insertSelective(order);        // 保存客户订单和物流产品关联信息        Long feeProductId = soiv.getFeeProductId();        sOrderProductService.add(order.getId(), feeProductId, soiv.getArriveDate());        long orderId = order.getId();        map.put("id", orderId);        map.put("ordercode", order.getOrderCode());        LOGGER.info("SalesOrderServiceImpl.create insertSelective return : {}", orderId);        // 保存订单流转状态变更        orderStatusLogService.insertSelective(orderId, StatusCategoryEnum.PROCESS, COrderStatusEnum.SAVED, false, null);        // 保存订单车辆信息        this.buildVehicles(vehiclesBrandList, order.getId(),                order.getEstValue().divide(BigDecimal.valueOf(order.getAmount()), 0, RoundingMode.UP));        // 保存用户常用车辆        this.addUserVehicles(userId, vehiclesBrandList);        // 计算订单费用        Map<String, Object> feesMap = this.computeFees(orderId, order.getIsPick(), order.getIsDeliv(), feeProductId, true);        map.putAll(feesMap);        return map;    }    @Override    public Map<String, Object> add(OrderForm form) throws Exception {        LOGGER.info("SalesOrderServiceImpl.create params : {}", form);        Map<String, Object> map = new HashMap<String, Object>();        SOrder order = new SOrder();        UserVo userVo = userService.getCurrentUserVo();        Integer userType = userService.getCurrentUserVo().getType();        order.setUserId(userVo.getId());        order.setOrderCode(UniquenessFlagUnits.generateUniquenessFlag("CO"));        order.setIsPick(form.getIspick());        order.setIsDeliv(form.getIsdeliv());        order.setDeliveryDate(form.getDeliverydate());        order.setDeliveryTime(form.getDeliveryTime());        order.setArriveDate(form.getArrivedate());        order.setArriveTime(form.getArriveTime());        order.setIsSencondhand(form.getIssencondhand());        order.setIsMobile(form.getIsmobile());        order.setEstValue(form.getEstvalue());        order.setIsAppoint(form.getAppoint());        order.setIsTicket(form.getTicket());        order.setIsUrgent(form.getIsUrgent());        order.setTransportType(form.getTransportType());        order.setOrderType(userType);        // 地址赋值        this.reSetAddressInOrder(order, form.getDepartaddrid(), userVo.getId(), AddressTypeEnum.SHIP.getValue());        this.reSetAddressInOrder(order, form.getReceiptaddrid(), userVo.getId(), AddressTypeEnum.RECEIPT.getValue());        // 保存状态、未付款状态        order.setStatus(COrderStatusEnum.SAVED.getValue());        order.setPayStatus(PaymentStatusEnum.UNPAID.getValue());        // 计算运距        SUserAddr depa = userAddressMapper.selectByPrimaryKey(form.getDepartaddrid());        SUserAddr rece = userAddressMapper.selectByPrimaryKey(form.getReceiptaddrid());        order.setDistance(                mapService.distance(depa.getCountyCode(), new StringBuilder(depa.getProvinceName()).append(depa.getCityName()).append(depa.getCountyName()).toString(), rece.getCountyCode(),                        new StringBuilder(rece.getProvinceName()).append(rece.getCityName()).append(rece.getCountyName()).toString()));        // 计算车辆总数        int amount = 0;        List<VehiclesBrandVo> vehiclesBrandList = JSONArray.parseArray(form.getVehiclesbrands(), VehiclesBrandVo.class);        for (VehiclesBrandVo vbv : vehiclesBrandList) {            amount += vbv.getVehiclecount();        }        order.setAmount(amount);        // 保存订单        sOrderMapper.insertSelective(order);        //保存客户订单和物流产品关联信息        if (null != form.getProductid()) {            sOrderProductService.add(order.getId(), form.getProductid(), form.getArrivedate());        }        long orderId = order.getId();        map.put("id", orderId);        map.put("ordercode", order.getOrderCode());        LOGGER.info("SalesOrderServiceImpl.create insertSelective return : {}", orderId);        // 保存订单流转状态变更        orderStatusLogService.insertSelective(orderId, StatusCategoryEnum.PROCESS, COrderStatusEnum.SAVED, false, null);        // 保存订单车辆信息        this.buildVehicles(vehiclesBrandList, order.getId(), order.getEstValue().divide(BigDecimal.valueOf(order.getAmount()), 0, RoundingMode.UP));        // 保存用户常用车辆        this.addUserVehicles(userVo.getId(), vehiclesBrandList);        // 计算订单费用        Map<String, Object> feesMap = this.computeFees(orderId, order.getIsPick(), order.getIsDeliv(), form.getProductid(), true);        map.putAll(feesMap);        // 发送短信通知 2017-08-30 候建慧        sendMessageDispatch(order);        return map;    }    /**     * 给调度人员发送短信通知     *     * @param order     */    private void sendMessageDispatch(SOrder order) {        // 获取调度人员手机号        List<BCode> codes = codeService.getBCodeByClassCode("DISPATCH");        if (CollectionUtils.isNotEmpty(codes)) {            codes.stream().forEach(item -> {                sendMessageService.createOrderSendMessageToDispatch(TmsUrlConstant.BMS_SERVICE + order.getId(), item.getCode());            });        }    }    /**     * @param vehiclesBrandList 车辆信息     * @param id                订单id     * @param vehiclesBrandList     * @Title: buildVehicles     * @Description: 保存订单车辆信息（s_order_detail、s_order_vin）     * @return: void     */    private void buildVehicles(List<VehiclesBrandVo> vehiclesBrandList, long id, BigDecimal estValue) {        LOGGER.info("orderServiceImple:buildVehicles vehiclesBrandList: {}, orderid:{}, estValue:{}", JSON.toJSONString(vehiclesBrandList), id, estValue);        // 保存订单的车辆        BVehicle vehicle = null;        BVehicleBrand vehicleBrand = null;        for (VehiclesBrandVo vbv : vehiclesBrandList) {            // 添加订单（车辆）详情            SOrderDetail od = new SOrderDetail();            od.setOrderId(id);            // 根据id获取车型信息和品牌信息            vehicle = vehicleMapper.selectByPrimaryKey(vbv.getVehicleid());            if (vehicle == null) {                LOGGER.error("vehicle is null");                throw new BusinessException("获取车型信息失败！");            }            vehicleBrand = brandMapper.selectByPrimaryKey(vehicle.getBrandId());            if (vehicleBrand == null) {                LOGGER.error("vehicleBrand is null");                throw new BusinessException("获取品牌信息失败！");            }            od.setVehicleId(vehicle.getId());            od.setVehicleName(vehicle.getVehicleName());            od.setBrandId(vehicleBrand.getId());            od.setBrandName(vehicleBrand.getBrandName());            od.setAmount(vbv.getVehiclecount());            BVehicleClass bVehicleClass = bVehicleClassService.getByVehicleClass(StringUtils.isBlank(vehicle.getSysVehicleClass()) == true ? BVehicleConstant.DEFAULT_VEHICLE_CLASS : vehicle.getSysVehicleClass());            od.setSysVehicleClass(bVehicleClass.getVehicleClass());            od.setSysVehicleClassid(bVehicleClass.getId());            int count = orderDetailMapper.insertSelective(od);            List<VinVo> vins = JSONArray.parseArray(vbv.getVins(), VinVo.class);            if (CollectionUtils.isNotEmpty(vins)) {                //判断vin号是否重复                List<VinVo> list = vins.stream().distinct().collect(Collectors.toList());                if (list.size() != vins.size()) {                    LOGGER.error("buildVehicles vin must not be Repeated");                    throw new IllegalArgumentException("vin号不能重复！");                }                for (int i = 0; i < vins.size(); i++) {                    SOrderVin vin = new SOrderVin();                    VinVo vinVo = vins.get(i);                    vin.setOrderId(id);                    vin.setDetailId(od.getId());                    vin.setVin(vinVo.getVin());                    vin.setEstValue(estValue);                    vin.setColor(                            StringUtils.isNotBlank(vins.get(i).getColor()) == false ? null : vins.get(i).getColor());                    vinMapper.insertSelective(vin);                }            }            LOGGER.info("SalesOrderServiceImpl.add insertSelective return : {}", count);        }    }    /**     * 获取用户地址到订单     *     * @param order     订单对象     * @param addressId 发货地址编码     * @param userId     */    public void reSetAddressInOrder(SOrder order, long addressId, long userId) {        SUserAddrExample example = new SUserAddrExample();        example.createCriteria().andUserIdEqualTo(userId).andIdEqualTo(addressId);        List<SUserAddr> list = userAddressMapper.selectByExample(example);        if (CollectionUtils.isEmpty(list)) {            LOGGER.error("User address is null!");            throw new BusinessException("地址id错误！");        }        SUserAddr ua = list.get(0);        // 发货地址        if (ua.getAddressType().equals(AddressTypeEnum.SHIP.getValue() + "")) {            order.setDepartAddrId(addressId);            order.setDepartProvinceCode(ua.getProvinceCode());            order.setDepartProvinceName(ua.getProvinceName());            order.setDepartCityCode(ua.getCityCode());            order.setDepartCityName(ua.getCityName());            order.setDepartCountyCode(ua.getCountyCode());            order.setDepartCountyName(ua.getCountyName());            order.setDepartUnit(ua.getUnitName());            if (ua.getProvinceName().equals(ua.getCityName())) {                order.setDepartAddr(ua.getCityName() + ua.getAddress());            } else {                order.setDepartAddr(ua.getProvinceName() + ua.getCityName() + ua.getAddress());            }            order.setDepartContact(ua.getContact());            order.setDepartPhone(ua.getPhone());            // 收货地址        } else if (ua.getAddressType().equals(AddressTypeEnum.RECEIPT.getValue() + "")) {            order.setReceiptAddrId(addressId);            order.setReceiptProvinceCode(ua.getProvinceCode());            order.setReceiptProvinceName(ua.getProvinceName());            order.setReceiptCityCode(ua.getCityCode());            order.setReceiptCityName(ua.getCityName());            order.setReceiptCountyCode(ua.getCountyCode());            order.setReceiptCountyName(ua.getCountyName());            order.setReceiptUnit(ua.getUnitName());            if (ua.getProvinceName().equals(ua.getCityName())) {                order.setReceiptAddr(ua.getCityName() + ua.getAddress());            } else {                order.setReceiptAddr(ua.getProvinceName() + ua.getCityName() + ua.getAddress());            }            order.setReceiptContact(ua.getContact());            order.setReceiptPhone(ua.getPhone());        }    }    public void reSetAddressInOrder(SOrder order, long addressId, long userId, int addressType) {        SUserAddrExample example = new SUserAddrExample();        example.createCriteria().andUserIdEqualTo(userId).andIdEqualTo(addressId);        List<SUserAddr> list = userAddressMapper.selectByExample(example);        if (CollectionUtils.isEmpty(list)) {            LOGGER.error("User address is null!");            throw new BusinessException("地址id错误！");        }        SUserAddr ua = list.get(0);        // 发货地址        if (Objects.equals(addressType, AddressTypeEnum.SHIP.getValue())) {            order.setDepartAddrId(addressId);            order.setDepartProvinceCode(ua.getProvinceCode());            order.setDepartProvinceName(ua.getProvinceName());            order.setDepartCityCode(ua.getCityCode());            order.setDepartCityName(ua.getCityName());            order.setDepartCountyCode(ua.getCountyCode());            order.setDepartCountyName(ua.getCountyName());            order.setDepartUnit(ua.getUnitName());            if (ua.getProvinceName().equals(ua.getCityName())) {                order.setDepartAddr(ua.getCityName() + ua.getAddress());            } else {                order.setDepartAddr(ua.getProvinceName() + ua.getCityName() + ua.getAddress());            }            order.setDepartContact(ua.getContact());            order.setDepartPhone(ua.getPhone());            // 收货地址        } else if (Objects.equals(addressType, AddressTypeEnum.RECEIPT.getValue())) {            order.setReceiptAddrId(addressId);            order.setReceiptProvinceCode(ua.getProvinceCode());            order.setReceiptProvinceName(ua.getProvinceName());            order.setReceiptCityCode(ua.getCityCode());            order.setReceiptCityName(ua.getCityName());            order.setReceiptCountyCode(ua.getCountyCode());            order.setReceiptCountyName(ua.getCountyName());            order.setReceiptUnit(ua.getUnitName());            if (ua.getProvinceName().equals(ua.getCityName())) {                order.setReceiptAddr(ua.getCityName() + ua.getAddress());            } else {                order.setReceiptAddr(ua.getProvinceName() + ua.getCityName() + ua.getAddress());            }            order.setReceiptContact(ua.getContact());            order.setReceiptPhone(ua.getPhone());        }    }    @Override    public int publish(long orderid, boolean b) throws Exception {        LOGGER.info("SalesOrderServiceImpl.updateById param : {}", orderid);        SOrderExample search = new SOrderExample();        if (b) {            search.createCriteria().andStatusEqualTo(COrderStatusEnum.CANCELED.getValue()).andIdEqualTo(orderid);        } else {            search.createCriteria().andStatusEqualTo(COrderStatusEnum.SAVED.getValue()).andIdEqualTo(orderid);        }        List<SOrder> orders = sOrderMapper.selectByExample(search);        if (CollectionUtils.isEmpty(orders)) {            LOGGER.error("orders is empty");            throw new BusinessException("发布失败！");        }        SOrder order = orders.get(0);        order.setStatus(COrderStatusEnum.WAIT_RECEIVE.getValue());        sOrderMapper.updateByPrimaryKeySelective(order);        // 不是重新发布则生成司机运单        if (!b) {            //生成服务订单            this.buildServiceOrder(order, null);        } else {            //如果是重新发布则更新服务订单装态为待调度            sServiceOrderService.updateStatusByCOrder(order.getId(), SServiceOrderStatusEnum.WAIT_DISPATCH.getValue());        }        // redis存储订单发布有效期        // this.saveOrderToRedis(orderid.toString(), new Date());        // 发送短信通知 2017-08-30 候建慧        sendMessageDispatch(order);        // 保存状态变更        return orderStatusLogService.insertSelective(orderid, StatusCategoryEnum.PROCESS, COrderStatusEnum.WAIT_RECEIVE,                false, null);    }    /**     * @param orderid 客户订单id     * @param b       是否是重新发布     * @param user     * @Title: kylePublish     * @Description: 发布订单 托运个人支付成功 调用发布订单接口     * @return: int     */    @Override    public int kylePublish(long orderid, boolean b, UserVo user) throws Exception {        LOGGER.info("SalesOrderServiceImpl.updateById param : {}", orderid);        SOrderExample search = new SOrderExample();        if (b) {            search.createCriteria().andStatusEqualTo(COrderStatusEnum.WAIT_RECEIVE.getValue()).andIdEqualTo(orderid);        } else {            search.createCriteria().andStatusEqualTo(COrderStatusEnum.SAVED.getValue()).andIdEqualTo(orderid);        }        List<SOrder> orders = sOrderMapper.selectByExample(search);        if (CollectionUtils.isEmpty(orders)) {            LOGGER.error("orders is empty");            throw new BusinessException("发布失败！");        }        SOrder order = orders.get(0);        order.setStatus(COrderStatusEnum.WAIT_RECEIVE.getValue());        sOrderMapper.updateByPrimaryKeySelective(order);        // 不是重新发布则生成司机运单        if (!b) {            //生成服务订单            this.buildServiceOrder(order, user);        }        // redis存储订单发布有效期        // this.saveOrderToRedis(orderid.toString(), new Date());        // 保存状态变更        return orderStatusLogService.insertSelective(orderid, StatusCategoryEnum.PROCESS, COrderStatusEnum.WAIT_RECEIVE,                false, user);    }    private void buildServiceOrder(SOrder order, UserVo user) throws Exception {        SServiceOrder sOrder = new SServiceOrder();        SOrderVin vin;        List<SOrderVin> vins = sOrderVinService.getList(order.getId());//      List<SOrderDetail> details = sOrderDetailService.getDetailsByOrderId(order.getId());        List<SServiceOrderStatusLog> statusList = new ArrayList<>();        if (null == user) {            user = userService.getCurrentUserVo();        }        for (int i = 0; i < vins.size(); i++) {            BeanUtils.copyProperties(order, sOrder);            vin = vins.get(i);            sOrder.setStatus(SServiceOrderStatusEnum.WAIT_DISPATCH.getValue());            sOrder.setDispatchTimes(0);//调度次数默认0            sOrder.setEstValue(vin.getEstValue());            sOrder.setCustomerOrderId(order.getId());            sOrder.setAmount(1);            sOrder.setOrderCode(UniquenessFlagUnits.generateUniquenessFlag("SO"));            sOrder.setCurrentAddr(order.getDepartCityName());            sOrder.setIsVeneer(order.getIsVeneer());            sServiceOrderService.add(sOrder);            SOrderDetail detail = sOrderDetailService.getById(vin.getDetailId());            //保存服务订单车辆信息            SServiceOrderVehicle vehicle = new SServiceOrderVehicle();            vehicle.setServiceOrderId(sOrder.getId());            vehicle.setBrandId(detail.getBrandId());            vehicle.setVehicleId(detail.getVehicleId());            vehicle.setVin(vin.getVin());            vehicle.setSysVehicleClassid(detail.getSysVehicleClassid());            vehicle.setSysVehicleClass(detail.getSysVehicleClass());            sServiceOrderVehicleService.add(vehicle);            //计算车辆运输费            if (order.getIsVeneer()) {                Map map = feesService.queryIntracityFees(order.getDepartCityCode(), order.getDistance(), 1, sOrderTrailerService.getBySOrderId(order.getId()).getbTrailerTypeId());                sOrder.setCost((BigDecimal) map.get("actualTotal"));                //保存服务订单费用详情                List<SOrderFeeDetailVo> fees = (List<SOrderFeeDetailVo>) map.get("fees");                if (CollectionUtils.isNotEmpty(fees)) {                    fees.forEach(fee -> sServiceOrderFeedetailService.addFeeDetail(sOrder.getId(), fee.getId(), fee.getFeeName(), fee.getCost(), fee.getActualAmount()));                }            } else {                sOrder.setCost(sServiceOrderService.computeFees(order, sOrder, vehicle, order.getIsPick(), order.getIsDeliv(), true));            }            //状态变更            SServiceOrderStatusLog log = new SServiceOrderStatusLog();            log.setServiceOrderId(sOrder.getId());            log.setStatus(sOrder.getStatus());            log.setUserId(user.getId());            log.setUserName(user.getUsername());            statusList.add(log);        }        //保存服务订单状态变更        sServiceOrderStatusLogService.batchAdd(statusList);    }    @Override    public OrderVo getById(long id, Boolean hasContainsInvoiceFee) {        LOGGER.info("SalesOrderServiceImpl.getById param : {}", id);        if (0 == id) {            LOGGER.error("id must not be 0");            throw new IllegalArgumentException("客户订单id不能是0");        }        // 当前用户信息        // UserVo userVo = userService.getCurrentUserVo();        OrderVo order = orderViewMapper.selectById(id);        if (order == null) {            LOGGER.error("order is null");            throw new BusinessException("获取订单信息失败！");        }        order.setStatusText(COrderStatusEnum.getByValue(order.getStatus()).getText()); // 添加页面状态文字显示        order.setPayStatusText(PaymentStatusEnum.getByValue(order.getPayStatus()).getText());// 添加页面支付状态文字显示        //拼接省市或市区        if (order.getIsVeneer()) {            order.setOrgin(order.getDepartCityName() + CONTACT_SYMBOL + order.getDepartCountyName());            order.setDest(order.getReceiptCityName() + CONTACT_SYMBOL + order.getReceiptCountyName());        } else {            order.setOrgin(order.getDepartCityName());            order.setDest(order.getReceiptCityName());        }        //查询客户订单的服务订单的车辆信息        List<SOrderDetailVo> svehicles = sServiceOrderVehicleService.getListByCOrderId(order.getId(), null, null);        //客户订单车辆信息        List<COrderDetailVo> vehicles = order.getVehicles();        if (CollectionUtils.isNotEmpty(vehicles)) {            int count = vehicles.stream().mapToInt(vehicle -> vehicle.getAmount()).sum();            order.setDetail(                    new StringBuffer().append(vehicles.size()).append("个品牌").append("  " + count).append("辆车").toString());        }        if (CollectionUtils.isEmpty(svehicles)) {            svehicles = new ArrayList<>();            for (int i = 0; i < vehicles.size(); i++) {                COrderDetailVo co = vehicles.get(i);                for (int j = 0; j < co.getVinList().size(); j++) {                    VinVo vinVo = co.getVinList().get(j);                    SOrderDetailVo sv = new SOrderDetailVo();                    sv.setAmount(1);                    sv.setVin(vinVo.getVin());                    sv.setBrandLogo(co.getBrandLogo());                    sv.setBrandName(co.getBrandName());                    sv.setVehicleName(co.getVehicleName());                    sv.setStatus(order.getStatus());                    sv.setStatusText(order.getStatusText());                    svehicles.add(sv);                }            }        }        order.setVehicles(null);        svehicles.forEach(vo -> {            if (order.getIsSencondhand()) {                vo.setTypeStatus("二手车");            } else {                vo.setTypeStatus("新车");            }            if (order.getIsMobile()) {                vo.setTypeStatus(vo.getTypeStatus() + " 能动");            } else {                vo.setTypeStatus(vo.getTypeStatus() + " 不能动");            }            if (StringUtils.isNotBlank(vo.getBrandLogo())) {                vo.setBrandLogo(QiniuUtils.generateDownloadTicket(HYCUtils.getConstantPropertiesLoader().getProperty(QiniuConstant.QINIU_LOGO_BUCKET),                        vo.getBrandLogo(), "", "", ""));            }        });        order.setSvehicles(svehicles);        //查询客户订单费用详情        List<SOrderFeeDetailVo> fees = sOrderFeeDetailService.getAllFeesBySOrder(order.getId(), order.getIsVeneer(), hasContainsInvoiceFee);        order.setFeeDetail(fees);        //获取折扣信息        BActivity activity = bActivityService.getByTypeAndClass(0, BActivityTypeEnum.FEE_DISCOUNT.getValue(), BActivityClassEnum.DISCOUNT.getValue());        SOrderDiscountVo discountDetail = order.getDiscount();        if (null != activity) {            discountDetail.setId(activity.getId());            discountDetail.setDesc(activity.getDescription());            discountDetail.setDiscount(true);            discountDetail.setCost(order.getActualCost());        } else {            discountDetail.setDiscount(false);        }        //查询积分抵扣金额信息(未支付计算，已支付查询)        /** 托运个人下单支付的时候 查询每单积分可抵扣金额 20161019注释lm */        /** QueryScoresVo scoresVo;         if(PaymentStatusEnum.ALREADY_PAID.getValue()==order.getPayStatus()){         scoresVo = paymentmentService.getOrderCost(order.getId());         }else{         // 查询可用积分         // scoresVo = this.getBScoresService().computeOrderAmountByScores(order.getId(), userVo.getId(), userVo.getType(), order.getOrderCost());         scoresVo = this.getBScoresService().computeOrderAmountByScores(order.getId(), userVo.getId(), userVo.getType(), order.getActualCost());         }         order.setScores(scoresVo); */        // 获取运单附件//      if (CollectionUtils.isEmpty(order.getReceiptPics()) || CollectionUtils.isEmpty(order.getReceivePics())) {//          Map<String, List<AttachVo>> attachsMap = waybillAttachService.getAttachs(id);//          if (CollectionUtils.isNotEmpty(attachsMap.get("sendPics"))) {//              order.setReceiptPics(attachsMap.get("sendPics"));//          }//          if (CollectionUtils.isNotEmpty(attachsMap.get("deliverPics"))) {//              order.setReceivePics(attachsMap.get("deliverPics"));//          }//      }////      // 提车照片//      List<AttachVo> loadPics = order.getReceiptPics();//      if (CollectionUtils.isNotEmpty(loadPics)) {//          AttachVo attach = null;//          for (int i = 0; i < loadPics.size(); i++) {//              attach = loadPics.get(i);//              attach.setPicKey(QiniuUtils.generateDownloadTicket(attach.getPicKey(), ""));//              attach.setTypeText(AttachTypeEnum.getByValue(attach.getType()).getText());//          }//      }////      // 收车照片//      List<AttachVo> unloadPics = order.getReceivePics();//      if (CollectionUtils.isNotEmpty(unloadPics)) {//          AttachVo attach = new AttachVo();//          for (int i = 0; i < unloadPics.size(); i++) {//              attach = unloadPics.get(i);//              attach.setPicKey(QiniuUtils.generateDownloadTicket(attach.getPicKey(), ""));//              attach.setTypeText(AttachTypeEnum.getByValue(attach.getType()).getText());//          }//      }        // 查询已付和未付费用//      if (order.getPayStatus() == PaymentStatusEnum.ALREADY_PAID.getValue()) {//          Map<String, BigDecimal> map = cAccntTurnOverService.selectDriverOrderAmount(userVo.getId(), id);//          order.setPaidCost(map.get("paid"));//          order.setUnpaidCost(map.get("unpaid"));//      }        // 查询承运人信息//      if (order.getStatus() >= COrderStatusEnum.CONFIRMED.getValue()//              && order.getStatus() < SServiceOrderStatusEnum.CANCELED.getValue()) {//          // 查询运单id--查询被选择的竞价单--查询司机信息//          CWaybillExample waybillExample = new CWaybillExample();//          waybillExample.createCriteria().andOrderIdEqualTo(id).andStatusEqualTo(order.getStatus());//          List<CWaybill> waybills = cWaybillMapper.selectByExample(waybillExample);//          if (CollectionUtils.isEmpty(waybills)) {//              logger.error("waybills is empty");//              throw new BusinessException("获取运单信息失败！");//          }////          CWaybillBidExample example = new CWaybillBidExample();//          example.createCriteria().andOrderIdEqualTo(id).andWaybillIdEqualTo(waybills.get(0).getId())//                  .andStatusEqualTo(true);//          List<CWaybillBid> waybillBids = cWaybillBidMapper.selectByExample(example);//          if (CollectionUtils.isEmpty(waybillBids)) {//              logger.error("waybillBids is empty");//              throw new BusinessException("获取运单竞价记录失败！");//          }////          CTruckInfoExample truckInfoExample = new CTruckInfoExample();//          truckInfoExample.createCriteria().andUserIdEqualTo(waybillBids.get(0).getActDriver())//                  .andStatusEqualTo(TruckAuditStatusEnum.AUDIT_PASS.getValue());//          List<CTruckInfo> truckInfos = truckInfoMapper.selectByExample(truckInfoExample);//          if (CollectionUtils.isEmpty(truckInfos)) {//              logger.error("truckInfos is empty");//              throw new BusinessException("车辆信息未审核通过！");//          }//          CTruckInfo truckInfo = truckInfos.get(0);////          SUser user = userService.getById(truckInfo.getUserId());////          DriverInfo driver = new DriverInfo();//          driver.setName(user.getRealName());//          driver.setPhone(user.getPhone());//          driver.setTruckNo(truckInfo.getTractorNumber());//          driver.setTruckType(truckInfo.getBoxTypeDesc());//          order.setDriverInfo(driver);//      }        return order;    }    /**     * 保存订单到Redis中     *     * @return     */    @Deprecated    @Override    public void saveOrderToRedis(String orderid, Date createDate) {        LOGGER.info("SalesOrderServiceImpl.saveOrderToRedis params : {},{}", orderid, createDate);        String key = App.OrderPublishOrderidsKey;        Jedis jedis = connectionFactory.fetchJedisConnector();        try {            // 添加field/value到hash表中，若key不存在则创建，若field存在则覆盖旧值            // 如果 field 是哈希表中的一个新建域，并且值设置成功，返回 1 。            // 如果哈希表中域 field 已经存在且旧值已被新值覆盖，返回 0 。            jedis.hset(key, orderid, String.valueOf(createDate.getTime()));        } catch (Exception e) {            LOGGER.error("SalesOrderServiceImpl.saveOrderToRedis error : {}", e);            throw new BusinessException("Redis中增加新发布订单" + orderid + "失败！");        } finally {            jedis.close();        }    }    /**     * 从Redis中清除订单     *     * @return     */    @Deprecated    @Override    public boolean cleanOrderFromRedis(String orderid) {        String key = App.OrderPublishOrderidsKey;        LOGGER.info("SalesOrderServiceImpl.cleanOrderToRedis param : {}", orderid);        Jedis jedis = connectionFactory.fetchJedisConnector();        try {            long result = jedis.hdel(key, orderid);            return result > 0;        } catch (Exception e) {            LOGGER.error("SalesOrderServiceImpl.cleanOrderToRedis error : {}", e);            throw new BusinessException("Redis清除订单" + orderid + "失败！");        } finally {            jedis.close();        }    }    @Override    public boolean cancel(long customerOrderId, String reason, boolean isSystem) throws Exception {        LOGGER.info("SalesOrderServiceImpl.cancel params : {}, {}", customerOrderId, reason);        // 获取客户订单信息        SOrder order = sOrderMapper.selectByPrimaryKey(customerOrderId);        if (order == null) {            LOGGER.error("cancel order is null");            throw new BusinessException("获取订单信息失败！");        }        // 如果服务订单已调度 则不能取消        sServiceOrderService.serviceOrderIsNotDispatch(customerOrderId);        // 状态为已保存、待接单且未付款时才可以取消        if ((order.getStatus() == COrderStatusEnum.SAVED.getValue() || order.getStatus() == COrderStatusEnum.WAIT_RECEIVE.getValue())                && order.getPayStatus() == PaymentStatusEnum.UNPAID.getValue()) {            order.setStatus(COrderStatusEnum.CANCELED.getValue());            order.setComment(reason);// 拒绝理由            sOrderMapper.updateByPrimaryKeySelective(order);            // 修改运单状态            // waybillService.updateStatusForOrder(order.getId(), COrderStatusEnum.CANCELED.getValue());            // 保存状态变更            orderStatusLogService.insertSelective(order.getId(), StatusCategoryEnum.PROCESS, COrderStatusEnum.CANCELED,                    isSystem, null);            //取消服务订单            sServiceOrderService.cancel(customerOrderId);            return true;        }        return false;    }    /**     * private List<Long> getSurplusTimeByOrder(List<String> lngOrderIds) {     * List<Long> listSurplusTime = Lists.newArrayList();     * if (!Collections3.isEmpty(lngOrderIds)) {     * for (int i = 0; i < lngOrderIds.size(); i++) {     * String orderid = lngOrderIds.get(i);     * Long lngCreateDate = this.getSurplusTimeByOrder(orderid);     * listSurplusTime.add(lngCreateDate);     * }     * }     * return listSurplusTime;     * }     */    @Deprecated    @Override    public long getSurplusTimeByOrder(String orderid) {        String key = App.OrderPublishOrderidsKey;        long surplusTime = 0L;        Jedis jedis = connectionFactory.fetchJedisConnector();        try {            String createDate = jedis.hget(key, orderid);            if (StringUtils.isNotBlank(createDate)) {                long lngCreateDate = Long.valueOf(createDate);                surplusTime = ((lngCreateDate + App.ORDER_EFFECTIVE_TIME * 1000) - new Date().getTime()) / 1000;                if (surplusTime < 0) {                    surplusTime = 0L;                    // 若订单发布时间已过期则立即取消订单                    this.cancel(Long.valueOf(orderid), null, true);                }            }        } catch (Exception e) {            LOGGER.error("SalesOrderServiceImpl.getSurplusTimeByOrder error : {}", e);            throw new BusinessException("查询订单" + orderid + "剩余时间失败！");        } finally {            jedis.close();        }        return surplusTime;    }    /**     * private List<OrderVo> checkPostTimeRemaining(List<OrderVo> orders, List<String> ids) {     * List<Long> list = getSurplusTimeByOrder(ids);     * if (CollectionUtils.isNotEmpty(list)) {     * for (int i = 0; i < orders.size(); i++) {     * orders.get(i).setPostTimeRemaining((int) Math.ceil(list.get(i) == 0 ? 0 : list.get(i) / 60));     * }     * }     * return orders;     * }     */    @Override    public boolean updateStatus(long orderId, int status, int payStatus, boolean flag) {        try {            // 更新订单状态            SOrder order = new SOrder();            order.setId(orderId);            order.setStatus(status);            if (0 != payStatus) {                order.setPayStatus(payStatus);            }            // 同步更新运单状态            sOrderMapper.updateByPrimaryKeySelective(order);            // 保存状态变更            if (0 != payStatus) {                orderStatusLogService.insertSelective(orderId, StatusCategoryEnum.PAY,                        PaymentStatusEnum.getByValue(payStatus));            }            orderStatusLogService.insertSelective(orderId, StatusCategoryEnum.PROCESS, COrderStatusEnum.getByValue(status),                    flag, null);            // 更新运单状态//          waybillService.updateStatusForOrder(orderId, status);            return true;        } catch (Exception e) {            LOGGER.error("SalesOrderServiceImpl.updateStatus error : {}", e);            throw new BusinessException("订单状态更新失败！");        }    }    @Override    public int getPayStatusById(long id) {        int intRtn = 0;        try {            Result<SOrder> orderResult = this.getOrderById(id);            if (orderResult != null) {                SOrder order = orderResult.getData();                if (order != null) {                    intRtn = order.getPayStatus();                }            }        } catch (Exception e) {            LOGGER.error("SalesOrderServiceImpl.getPayStatusById error : {}", e);            throw new BusinessException("查询失败！");        }        return intRtn;    }    @Override    public Result<SOrder> getOrderById(long id) {        LOGGER.info("SalesOrderServiceImpl.getById param : {}", id);        Result<SOrder> result = new Result<>(true, "查询成功！");        try {            SOrder order = sOrderMapper.selectByPrimaryKey(id);            result.setData(order);            return result;        } catch (Exception e) {            LOGGER.error("SalesOrderServiceImpl.getOrderById error : {}", e);            throw new BusinessException("查询失败！");        }    }    @Override    public boolean updateOrderPayStatusForRedis(long orderId, int paystatus) {        LOGGER.info("SalesOrderServiceImpl.updateOrderPayStatusForRedis param : {}, {}", orderId, paystatus);        SOrder order = sOrderMapper.selectByPrimaryKey(orderId);        if (order == null) {            throw new BusinessException("获取订单信息失败！");        }        this.updateStatus(orderId, COrderStatusEnum.IN_TRANSIT.getValue(), paystatus, true);        //支付完成推送通知//      CWaybill waybill = waybillService.getByOrderId(orderId);//      String msg="您的运单"+ waybill.getWaybillCode() +"，"+ waybill.getLoadCity() +"发往" + waybill.getUnloadCity() + " 支付成功 ，请您前往提车! ";//      pushService.notifyKyleUser( waybill.getActDriver(), msg );        return true;    }    @Override    public boolean confirmReceive(long id) throws Exception {        // 判断订单上个状态是否为已交车        SOrderExample example = new SOrderExample();        SOrderExample.Criteria criteria = example.createCriteria();        criteria.andIdEqualTo(id);        criteria.andStatusEqualTo(COrderStatusEnum.COMPLETED.getValue());        List<SOrder> sOrders = sOrderMapper.selectByExample(example);        if (CollectionUtils.isNotEmpty(sOrders)) {            //判断所有服务订单状态为交车时才可以交车并更新状态为已完成            if (sServiceOrderService.assertStatus(id, SServiceOrderStatusEnum.HAVE_DELIVERY.getValue())) {                sServiceOrderService.updateStatusByCOrder(id, SServiceOrderStatusEnum.DONE.getValue());            }            // 更新订单状态            this.updateStatus(id, COrderStatusEnum.DONE.getValue(), 0, false);            // SOrder sOrder = sOrders.get(0);            // 托运企业在订单完成的时候 账户增加积分 - (改为在月结算的时候抵扣和增加积分)            // this.getBScoresService().addTotalCost(sOrder.getId(), sOrder.getUserId(), sOrder.getOrderType(), sOrder.getActualCost());        } else {            LOGGER.info("confirmReceive order status is wrong");            throw new BusinessException("确认失败！");        }        return true;    }    @Override    public Map<String, Object> computeFees(Long id, Boolean isPick, Boolean isDeliv, Long productid, Boolean hasInvoice) throws Exception {        LOGGER.info("order cost order id:{}, isPick:{}, isDeliv:{}", id, isPick, isDeliv);        if (null == id) {            LOGGER.error("SalesOrderServiceImpl.countAllFees param id can not be null!");            throw new BusinessException("客户订单id不能为空！");        }        Map<String, Object> map = new HashMap<>();        SOrder order = this.selectByPrimaryKey(id);        if (order == null) {            LOGGER.error("order is null");            throw new BusinessException("获取订单信息失败！");        }        //计算运距        BigDecimal distance = mapService.distance(order.getDepartCountyCode(), new StringBuffer(order.getDepartProvinceName()).append(order.getDepartCityName())                        .append(order.getDepartCountyName()).toString(),                order.getReceiptCountyCode(), new StringBuffer(order.getReceiptProvinceName()).append(order.getReceiptCityName())                        .append(order.getReceiptCountyName()).toString());        //获取车辆信息        List<VehiClesInfoFrom> vehicles = new ArrayList<>();        //构建车型信息        List<SOrderDetail> details = sOrderDetailService.getDetailsByOrderId(id);        for (int i = 0; i < details.size(); i++) {            SOrderDetail detail = details.get(i);            for (int j = 0; j < detail.getAmount(); j++) {                VehiClesInfoFrom vehicle = new VehiClesInfoFrom();                vehicle.setAmount(1);                vehicle.setTypeId(detail.getSysVehicleClassid());                vehicle.setType(detail.getSysVehicleClass());                vehicles.add(vehicle);            }        }//      //如果是导入订单则查询是否已经匹配了配置模型//      SOrderImportedStowage importedStowage = sOrderImportedStowageService.getByImportedOrderId(id);//      BStowageModel stowageModel = null;//      if(null!=importedStowage){//          stowageModel = bStowageVehicleService.getById(importedStowage.getStowageModelId());//      }else{//      }        //匹配配置模型        List<Long> vehicleClassIds = details.stream().map(vehicle -> vehicle.getSysVehicleClassid()).collect(Collectors.toList());        List<Integer> vehicleNum = details.stream().mapToInt(vehicle -> vehicle.getAmount()).collect(ArrayList::new, ArrayList::add, ArrayList::addAll);        BStowageModel stowageModel = bStowageVehicleService.computeSuitableStowage(BStowageModelEnum.ORDER, vehicleClassIds, vehicleNum);        if (null != stowageModel) {            //保存配置模型和订单关联            sOrderStowageService.add(id, stowageModel.getId());        }        map = feesService.queryFees(order.getDepartCountyCode(), order.getReceiptCountyCode(), distance, stowageModel, productid, order.getDeliveryDate(), order.getDeliveryTime(), vehicles, order.getEstValue(), true, order.getIsPick(), order.getIsDeliv(), true, true);        @SuppressWarnings("unchecked")        List<SOrderFeeDetailVo> fees = (List<SOrderFeeDetailVo>) map.get("fees");        SOrderFeeDetailVo shippingFee = fees.stream().filter(fee -> BFeeTypeEnum.SHIPPING.getValue() == fee.getFeeCode()).collect(Collectors.toList()).get(0);        SOrderFeeDetailVo invoiceFee = fees.stream().filter(fee -> BFeeTypeEnum.INVOICE_TAX.getValue() == fee.getFeeCode()).collect(Collectors.toList()).get(0);        shippingFee.setCost(shippingFee.getCost().subtract(invoiceFee.getCost()));        shippingFee.setActualAmount(shippingFee.getActualAmount().subtract(invoiceFee.getActualAmount()));        order.setOrderCost(                BigDecimal.valueOf(fees.stream().mapToLong(fee -> fee.getCost().longValue()).sum()).setScale(2));        order.setActualCost(                BigDecimal.valueOf(fees.stream().mapToLong(fee -> fee.getActualAmount().longValue()).sum()).setScale(2));        order.setOrderCost((BigDecimal) map.get("total"));        order.setActualCost((BigDecimal) map.get("actualtotal"));        sOrderMapper.updateByPrimaryKeySelective(order);        //获取用户信息        // UserVo userVo = userService.getCurrentUserVo();        //获取折扣信息        BActivity activity = bActivityService.getByTypeAndClass(0, BActivityTypeEnum.FEE_DISCOUNT.getValue(), BActivityClassEnum.DISCOUNT.getValue());        SOrderDiscountVo discountDetail = new SOrderDiscountVo();        if (null != activity) {            discountDetail.setId(activity.getId());            discountDetail.setDesc(activity.getDescription());            discountDetail.setDiscount(true);            discountDetail.setCost(order.getActualCost());        } else {            discountDetail.setDiscount(false);        }        map.put("discount", discountDetail);        //查询积分抵扣金额信息(未支付计算，已支付查询)        /** 托运个人下单支付的时候 查询每单积分可抵扣金额 20161019注释lm */        /** QueryScoresVo scoresVo;         if(PaymentStatusEnum.ALREADY_PAID.getValue()==order.getPayStatus()){         scoresVo = paymentmentService.getOrderCost(order.getId());         }else{         // 查询可用积分         // scoresVo = this.getBScoresService().computeOrderAmountByScores(order.getId(), userVo.getId(), userVo.getType(), order.getOrderCost());         scoresVo = this.getBScoresService().computeOrderAmountByScores(order.getId(), userVo.getId(), userVo.getType(), order.getActualCost());         }         map.put("scoresVo", scoresVo); */        //保存费用详情        fees.forEach(fee -> sOrderFeeDetailService.addFeeDetail(id, fee.getId(), fee.getFeeCode(), fee.getFeeName(), fee.getCost(), fee.getActualAmount()));        //将税费加到运输费中        shippingFee.setCost(shippingFee.getCost().add(invoiceFee.getCost()));        shippingFee.setActualAmount(shippingFee.getActualAmount().add(invoiceFee.getActualAmount()));        fees.remove(invoiceFee);        return map;    }    public void addSorderDiscount(long orderId, long feeDiscountId) {        LOGGER.info("insert SOrderDiscount params, orderId:{}, feeDiscountId:{}.", orderId, feeDiscountId);        try {            SOrderDiscount sOrderDiscount = new SOrderDiscount();            sOrderDiscount.setCreateTime(new Date());            sOrderDiscount.setOrderId(orderId);            sOrderDiscount.setFeeDiscountId(feeDiscountId);            sOrderDiscountMapper.insertSelective(sOrderDiscount);        } catch (Exception e) {            LOGGER.error("insert SOrderDiscount error. {}", e);            e.printStackTrace();        }    }    @Override    public SOrder getUnpaidOrder(long customerOrderId) {        LOGGER.info("getUnpaidOrder param : {}", customerOrderId);        if (0 == customerOrderId) {            LOGGER.error("getUnpaidOrder customerOrderId must not be 0");            throw new IllegalArgumentException("客户订单id不能是0！");        }        //id 待付款状态 未付款状态 个人订单        SOrderExample example = new SOrderExample();        List<Integer> statusList = new ArrayList<>();        statusList.add(COrderStatusEnum.CONFIRMED.getValue());        statusList.add(COrderStatusEnum.WAIT_RECEIVE.getValue());        statusList.add(COrderStatusEnum.SAVED.getValue());        example.createCriteria().andIdEqualTo(customerOrderId).andStatusIn(statusList).andOrderTypeEqualTo(SOrderTypeEnum.PERSONAL.getValue()).andPayStatusEqualTo(PaymentStatusEnum.UNPAID.getValue());        List<SOrder> list = sOrderMapper.selectByExample(example);        if (CollectionUtils.isEmpty(list)) {            LOGGER.error("getUnpaidOrder List is empty");            throw new BusinessException("获取未付款订单信息失败！");        }        return list.get(0);    }    @Override    public COrderLogisticsVo getSOrderByCOrderId(long customerOrderId) throws Exception {        LOGGER.info("getSOrderByCOrderId param : {}", customerOrderId);        if (0 == customerOrderId) {            LOGGER.error("getSOrderByCOrderId customerOrderId must not be 0");            throw new IllegalArgumentException("客户订单id不能是0！");        }        Map<String, Object> paramsMap = new HashMap<>();        Long userId = userService.getCurrentUserVo().getId();        paramsMap.put("customerOrderId", customerOrderId);        BCompanyUser companyUser = bCompanyUserService.getCompanyByUserId(userId);        List<BCompanyUser> bCompanyUsers = null;        if (null != companyUser.getDivisionId()) {            bCompanyUsers = bCompanyUserService.getListByDivisionId(companyUser.getDivisionId());        } else {            bCompanyUsers = bCompanyUserService.getListByCompanyId(companyUser.getCompanyId());        }        List<Long> userList = new ArrayList<>();        for (BCompanyUser bCompanyUser : bCompanyUsers) {            userList.add(bCompanyUser.getUserId());        }        paramsMap.put("userList", userList);        COrderLogisticsVo vo = orderViewMapper.selectListByCondition(paramsMap);        if (null != vo) {            if (vo.getIsVeneer()) {                vo.setOrgin(vo.getDepartCityName() + CONTACT_SYMBOL + vo.getDepartCountyName());                vo.setDest(vo.getReceiptCityName() + CONTACT_SYMBOL + vo.getReceiptCountyName());            } else {                vo.setOrgin(vo.getDepartCityName());                vo.setDest(vo.getReceiptCityName());            }            List<SServiceOrderVo> sorders = vo.getSorders();            if (CollectionUtils.isNotEmpty(sorders)) {                sorders.forEach(order -> order.setStatustext(SServiceOrderStatusEnum.getByValue(order.getStatus()).getText()));            }            return vo;        }        return null;    }    /**     * 根据服务订单ID 修改客户订单状态     *     * @param sorderId     * @return     */    @Override    public boolean updateOrderStatusBySid(Long sorderId) {        boolean flag = false;        try {            LOGGER.info("udpate sorder status by service order id params sorderId : {}.", sorderId);            SServiceOrder sServiceOrder = sServiceOrderService.selectById(sorderId);            SOrder order = sOrderMapper.selectByPrimaryKey(sServiceOrder.getCustomerOrderId());            if (order.getStatus() == COrderStatusEnum.WAIT_RECEIVE.getValue()) {                if (order.getOrderType() == OrderTypeEnum.PERSONAL.getValue()) {                    // 个人下单 订单状态：待支付                    order.setStatus(COrderStatusEnum.CONFIRMED.getValue());                    String msg = "您的订单" + order.getOrderCode() + "，" + order.getDepartCityName() + "发往"                            + order.getReceiptCityName() + " 已有司机接单，请立即支付！";                    pushService.notifyKyleUser(order.getUserId(), msg);                } else {                    // 企业下单 订单状态：待提车                    order.setStatus(COrderStatusEnum.IN_TRANSIT.getValue());                }                sOrderMapper.updateByPrimaryKey(order);                this.addStatusLog(order.getId(), order.getStatus());            }        } catch (Exception e) {            LOGGER.error("udpate sorder status by service order id error : {}.", e);            throw new BusinessException("根据服务订单修改订单状态异常");        }        return flag;    }    /**     * 系统添加日志     *     * @param id     * @param status     */    private void addStatusLog(Long id, Integer status) {        try {            // 添加日志            SOrderStatusLog log = new SOrderStatusLog();            log.setCategory(StatusCategoryEnum.PROCESS.getValue());            log.setCreateTime(new Date());            log.setUpdateTime(new Date());            log.setOrderId(id);            log.setUserId(0L);            log.setUserName("admin");            log.setOperator(OrderStatusLogOperatorEnum.SYSTEM.getValue());            log.setStatus(status);            orderStatusLogService.insertSelective(log);        } catch (Exception e) {            LOGGER.error("update sorder status add log error : {}.", e);            throw new BusinessException("客户订单状态修改添加日志异常");        }    }    /**     * 60已发车(司机在承运端点击按钮)状态订单显示, (修改为70运输中)     */    @Override    public Map<String, Object> alreadystartList(PageVo page) throws Exception {        LOGGER.info("select order alreadystartList .params : {}.", COrderStatusEnum.IN_TRANSIT.getValue());        return selectByStatus(page, COrderStatusEnum.IN_TRANSIT.getValue());    }    /**     * 80已交车状态订单显示，(修改为90已完成)     */    @Override    public Object completedList(PageVo page) throws Exception {        LOGGER.info("select order completedList .params : {}.", COrderStatusEnum.COMPLETED.getValue());        return selectByStatus(page, COrderStatusEnum.COMPLETED.getValue());    }    /**     * 查询提车交车页面订单显示列表     */    @Override    public Map<String, Object> selectByStatus(PageVo page, int status) throws Exception {        LOGGER.info("select ordersList selectByStatus params orderStatus: {}.", status);        List<SOrder> orders = new ArrayList<SOrder>();        SOrderExample example = new SOrderExample();        // example.createCriteria().andStatusEqualTo(OrderStatusEnum.ALREADYSTART.getValue());        example.createCriteria().andStatusEqualTo(status);        example.setLimitStart(page.getStartIndex());        example.setLimitEnd(page.getPageSize());        if (StringUtils.isNotBlank(page.getOrder())) {            example.setOrderByClause(page.getOrder());        } else {            example.setOrderByClause("id DESC");        }        page.setTotalRecord(sOrderMapper.countByExample(example));        try {            orders = sOrderMapper.selectByExample(example);        } catch (Exception e) {            LOGGER.error("select ordersList selectByStatus params orderStatus: {}. ERROR: {}.", status, e);            e.printStackTrace();        }        LOGGER.info("select ordersList selectByStatus params orderStatus: {}. FINISH.", status);        Map<String, Object> map = new HashMap<String, Object>();        map.put("orderInfo", orders);        map.put("page", page);        return map;    }    /**     * 修改订单状态 共有方法  以发车  完成（已收车）     *     * @param id     * @param status     * @return     */    public Result<Object> changeStatus(Long id, int status) {        LOGGER.info("update order changeStatus params : id : {}, status : {}.", id, status);        Result<Object> result = new Result<Object>(true, "确认发车,修改订单状态成功.");        try {            SOrder order = sOrderMapper.selectByPrimaryKey(id);            LOGGER.info("update order changeStatus params : order : {}.", order);            order.setStatus(status);            int count = sOrderMapper.updateByPrimaryKey(order);            LOGGER.info("update order changeStatus params : orderid : {}, count : {}.", id, count);            CWaybillExample example = new CWaybillExample();            example.createCriteria().andOrderIdEqualTo(id);            CWaybill cWaybill = this.getCWaybillMapper().selectByExample(example).get(0);            cWaybill.setStatus(status);            int waybillCount = this.getCWaybillMapper().updateByPrimaryKeySelective(cWaybill);            LOGGER.info("update order-waybill changeStatus params : orderid : {}, waybillid : {}, waybillCount : {}.", id, cWaybill.getId(), waybillCount);            SOrderStatusLog log = new SOrderStatusLog();            log.setUserId(0L);            log.setUserName("admin");            log.setOrderId(order.getId());            log.setOperator(OrderStatusLogOperatorEnum.USER.getValue());            log.setCategory(StatusCategoryEnum.PROCESS.getValue());            log.setStatus(status);            this.getSOrderStatusLogMapper().insertSelective(log);            LOGGER.info("update order changeStatus insertLog params : orderid : {}, SOrderStatusLog : {}.", id, log);        } catch (Exception e) {            result.setMessage("确认发车,修改订单状态系统异常.");            result.setSuccess(false);            LOGGER.error("update order changeStatus ERROR.{}", e);            e.printStackTrace();        }        return result;    }    /**     * 确认发车     */    @Override    public Result<Object> changeStatus(Long id) {        LOGGER.info("update order changeStatus init INTRANSIT params id : {}, status : {}.", id, COrderStatusEnum.CONFIRMED.getValue());        return changeStatus(id, COrderStatusEnum.CONFIRMED.getValue());    }    /**     * 确认收车，订单完成     */    @Override    public Object changeStatusOrderDone(Long id) {        LOGGER.info("update order changeStatus init DONE params id : {}, status : {}.", id, COrderStatusEnum.DONE.getValue());        return this.changeStatus(id, COrderStatusEnum.DONE.getValue());    }    /**     * 查询提车照片     */    @Override    public Result<Object> selectTichePic(Long orderId, boolean flag) {        LOGGER.info("select selectTichePic params orderid : {}, flag : {}.", orderId, flag);        Result<Object> result = new Result<Object>();        try {            CWaybillExample example = new CWaybillExample();            example.createCriteria().andOrderIdEqualTo(orderId);            CWaybill cWaybill = this.getCWaybillMapper().selectByExample(example).get(0);            CWaybillAttachExample attachExample = new CWaybillAttachExample();            if (flag) {                LOGGER.info("select selectTichePic params orderid : {} pic type DELIVER : {}.", orderId, AttachCategoryEnumWaybill.DELIVER.getValue());                attachExample.createCriteria().andWaybillIdEqualTo(cWaybill.getId()).andCategoryEqualTo(AttachCategoryEnumWaybill.DELIVER.getValue());            } else {                LOGGER.info("select selectTichePic params orderid : {} pic type SEND : {}.", orderId, AttachCategoryEnumWaybill.SEND.getValue());                attachExample.createCriteria().andWaybillIdEqualTo(cWaybill.getId()).andCategoryEqualTo(AttachCategoryEnumWaybill.SEND.getValue());            }            List<CWaybillAttach> cWaybillAttachs = cWaybillAttachMapper.selectByExample(attachExample);            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();            for (CWaybillAttach cWaybillAttach : cWaybillAttachs) {                Map<String, Object> map = new HashMap<String, Object>();                map.put("key", cWaybillAttach.getPicKey());                map.put("url", QiniuUtils.generateDownloadTicket(cWaybillAttach.getPicKey(), ""));                map.put("desc", AttachCategoryEnumWaybill.SEND.getText());                map.put("orderId", orderId);                LOGGER.info("select selectTichePic params orderid : {}, cWaybillAttach : {}.", orderId, cWaybillAttach.getId());                list.add(map);            }            result.setData(list);        } catch (Exception e) {            LOGGER.error("select selectTichePic ERROR. {}", e);            e.printStackTrace();        }        return result;    }    /**     * 确认收车 上传照片存储照片信息     */    @Override    public Result<Object> saveOrderAttach(String key, int type, Long orderId) {        LOGGER.info("admin upload confirmDone pic: key:{},type:{},orderId:{}.", key, type, orderId);        Result<Object> result = new Result<Object>(true, "确认收车，后台上传照片成功。");        try {            CWaybillExample example = new CWaybillExample();            example.createCriteria().andOrderIdEqualTo(orderId);            CWaybill cWaybill = this.getCWaybillMapper().selectByExample(example).get(0);            CWaybillAttach cWaybillAttach = new CWaybillAttach();//          if(type == AttachTypeEnum.RECEIVE_BILL.getValue()){//              cWaybillAttach.setType(AttachTypeEnum.RECEIVE_BILL.getValue());//          } else{//              cWaybillAttach.setType(AttachTypeEnum.RECEIVE_PHOTO.getValue());//          }            cWaybillAttach.setWaybillId(cWaybill.getId());            cWaybillAttach.setCategory(AttachCategoryEnumWaybill.RECEIVE.getValue());            cWaybillAttach.setPicKey(key);            cWaybillAttach.setUserId(0L);            cWaybillAttach.setUserName("admin");            cWaybillAttach.setCreatTime(new Date());            cWaybillAttach.setUpdateTime(new Date());            // int count = cWaybillAttachMapper().insertSelective(cWaybillAttach);            // logger.info("admin upload confirmDone: {} nums.", count);            String url = QiniuUtils.generateDownloadTicket(key, "");            result.setData(url);            LOGGER.info("admin upload confirmDone picUrl:{}.", url);        } catch (Exception e) {            LOGGER.error("admin upload confirmDone Exception. {}", e);            result.setSuccess(false);            result.setMessage("上传图片系统异常。");            e.printStackTrace();        }        return result;    }    /**     * 订单列表明细显示     */    @Override    public SOrderInfoVo orderDetail(Long orderId) {        LOGGER.error("select ordersDetail by orderId params orderId : {}.", orderId);        SOrderInfoVo sOrderVo = null;        try {            sOrderVo = sOrderViewMapper.selectInfoByOrderId(orderId);            // 费用详情            /** List<SOrderFeedetailTypeIdVo> allFees = sOrderVo.getFeeDetails();             FeeDetailVo fee = sOrderVo.getFeeDetail();             SOrderFeedetailTypeIdVo feedetail = null;             for (int i = 0; i < allFees.size(); i++) {             feedetail = allFees.get(i);             if (feedetail.getFeeName().equals("运输费")) {             logger.error("select ordersDetail by orderId params orderId : {}, feedetails10 : {}.", orderId, feedetail.getMoney());             fee.setShippingfee(feedetail.getMoney().doubleValue());             } else if (feedetail.getFeeName().equals("保险费")) {             logger.error("select ordersDetail by orderId params orderId : {}, feedetails20 : {}.", orderId, feedetail.getMoney());             fee.setInsurance(feedetail.getMoney().doubleValue());             } else if (feedetail.getFeeName().equals("提车费")) {             logger.error("select ordersDetail by orderId params orderId : {}, feedetails40 : {}.", orderId, feedetail.getMoney());             fee.setExtractcost(feedetail.getMoney().doubleValue());             } else if (feedetail.getFeeName().equals("交车费")) {             logger.error("select ordersDetail by orderId params orderId : {}, feedetails50 : {}.", orderId, feedetail.getMoney());             fee.setReturncost(feedetail.getMoney().doubleValue());             }             }             fee.setTotal(sOrderVo.getOrderCost().doubleValue());             fee.setActualcost(sOrderVo.getActualCost().doubleValue());             sOrderVo.setFeeDetail(fee);             sOrderVo.setFeeDetails(null); */            // 客户订单 － 服务订单 － 运单明细 － 运单ID － 物流            LOGGER.error("select ordersDetail by orderId params orderId : {}, Tril", orderId);            SServiceOrderExample serviceOrderExample = new SServiceOrderExample();            serviceOrderExample.createCriteria().andCustomerOrderIdEqualTo(orderId);            List<SServiceOrder> serviceOrders = sServiceOrderService.selectByExample(serviceOrderExample);            List<SServiceOrderTrailVo> orderTrailVos = new ArrayList<SServiceOrderTrailVo>();            for (SServiceOrder sServiceOrder : serviceOrders) {                SServiceOrderTrailVo sServiceOrderTrailVo = new SServiceOrderTrailVo();                BeanUtils.copyProperties(sServiceOrder, sServiceOrderTrailVo);                SServiceOrderStatusLogExample serviceOrderStatusLogExample = new SServiceOrderStatusLogExample();                serviceOrderStatusLogExample.createCriteria().andServiceOrderIdEqualTo(sServiceOrder.getId());                List<SServiceOrderStatusLog> sOrderstatusLogs = sServiceOrderStatusLogMapper.selectByExample(serviceOrderStatusLogExample);                sServiceOrderTrailVo.setLogs(sOrderstatusLogs);                CWaybillDetailExample detailExample = new CWaybillDetailExample();                detailExample.createCriteria().andServiceOrderIdEqualTo(sServiceOrder.getId());                List<CWaybillDetail> details = cWaybillDetailMapper.selectByExample(detailExample);                List<CWaybillTrail> trails = new ArrayList<CWaybillTrail>();                for (CWaybillDetail cWaybillDetail : details) {                    // 使用运单明细查询与运单 ID 查询物流信息                    CWaybillTrailExample trailExample = new CWaybillTrailExample();                    trailExample.createCriteria().andWaybillIdEqualTo(cWaybillDetail.getWaybillId());                    trails.addAll(cWaybillTrailService.selectByExample(trailExample));                }                sServiceOrderTrailVo.setTrails(trails);                orderTrailVos.add(sServiceOrderTrailVo);            }            sOrderVo.setOrderTrailVos(orderTrailVos);            /** // 查询运单状态 － 物流跟踪             CWaybillDetailExample cWaybillDetailExample = new CWaybillDetailExample();             cWaybillDetailExample.createCriteria().andOrderIdEqualTo(orderId);             List<CWaybillDetail> list = this.getCWaybillDetailMapper().selectByExample(cWaybillDetailExample);             List<Long> waybillids = new ArrayList<Long>();             for (CWaybillDetail cWaybillDetail : list) {             if(!waybillids.contains(cWaybillDetail.getWaybillId())){             waybillids.add(cWaybillDetail.getWaybillId());             }             }             if(!CollectionUtils.isEmpty(waybillids)){             CWaybillExample cWaybillExample = new CWaybillExample();             cWaybillExample.createCriteria().andIdIn(waybillids);             List<CWaybillVo> cWaybills = this.getCWaybillViewMapper().selectByExample(cWaybillExample);             for (CWaybillVo cWaybillVo : cWaybills) {             cWaybillVo.setStatusText(OrderStatusEnum.getByValue(cWaybillVo.getStatus()).getText());             cWaybillVo.setPayStatusText(PaymentStatusEnum.getByValue(cWaybillVo.getPayStatus()).getText());             CWaybillDetailExample detailExample = new CWaybillDetailExample();             detailExample.createCriteria().andOrderIdEqualTo(orderId).andWaybillIdEqualTo(cWaybillVo.getId());             List<CWaybillDetail> details = this.getCWaybillDetailMapper().selectByExample(detailExample);             cWaybillVo.setcWaybillDetails(details);             }             sOrderVo.setcWaybillsVo(cWaybills);             } */        } catch (Exception e) {            LOGGER.error("select jidan chaidan ordersDetail ERROR. {}", e);            e.printStackTrace();        }        return sOrderVo;    }    /**     * 车保信息查询导出 共有查询数据方法     *     * @return     */    public List<CarInsuranceDetailsVo> getSOrders() {        LOGGER.info("select selectCarInsuranceDetails init getSOrders.");        SOrderExample example = new SOrderExample();        example.createCriteria().andPayStatusEqualTo(PaymentStatusEnum.ALREADY_PAID.getValue());        LOGGER.info("select selectCarInsuranceDetails init getSOrders. payStatus : {}.", PaymentStatusEnum.ALREADY_PAID.getValue());        List<SOrder> sOrders = null;        List<CarInsuranceDetailsVo> orders = new ArrayList<CarInsuranceDetailsVo>();        CarInsuranceDetailsVo carInsuranceDetailsVo = new CarInsuranceDetailsVo();        List<CarInfoVo> carInfoVos = new ArrayList<CarInfoVo>();        try {            sOrders = sOrderMapper.selectByExample(example);            for (SOrder sOrder : sOrders) {                Long orderId = sOrder.getId();                Date deliveryDate = sOrder.getDeliveryDate();                String departProvinceName = sOrder.getDepartProvinceName();                String receiptProvinceName = sOrder.getReceiptProvinceName();                LOGGER.info("select selectCarInsuranceDetails init getSOrders orderid : {}.", orderId);                CWaybillExample waybillExample = new CWaybillExample();                waybillExample.createCriteria().andOrderIdEqualTo(orderId);                CWaybill cWaybill = this.getCWaybillMapper().selectByExample(waybillExample).get(0);                Long waybillId = cWaybill.getId();                Long actDriverId = cWaybill.getActDriver();                LOGGER.info("select selectCarInsuranceDetails init getSOrders waybillId : {}.", waybillId);                SUserExample userExample = new SUserExample();                userExample.createCriteria().andIdEqualTo(actDriverId);                SUser sUser = userService.selectByExample(userExample).get(0);                String driverName = sUser.getRealName();                String driverPhone = sUser.getPhone();                LOGGER.info("select selectCarInsuranceDetails init getSOrders userid : {}, driverName : {}, driverPhone : {}.", actDriverId, driverName, driverPhone);                int amount = sOrder.getAmount();                BigDecimal estValuePrice = sOrder.getEstValue().divide(new BigDecimal(amount), 0, RoundingMode.UP);                LOGGER.info("select selectCarInsuranceDetails init getSOrders estValuePrice : {}.", estValuePrice);                SOrderFeedetailExample feedetailExample = new SOrderFeedetailExample();                feedetailExample.createCriteria().andOrderIdEqualTo(orderId).andFeeTypeIdEqualTo(20L);                SOrderFeedetail sOrderFeedetail = this.getSOrderFeedetailMapper().selectByExample(feedetailExample).get(0);                BigDecimal price = sOrderFeedetail.getMoney().divide(new BigDecimal(amount), 0, RoundingMode.UP);                SOrderDetailExample detailExample = new SOrderDetailExample();                detailExample.createCriteria().andOrderIdEqualTo(orderId);                List<SOrderDetail> sOrderDetails = this.getSOrderDetailMapper().selectByExample(detailExample);                for (SOrderDetail sOrderDetail : sOrderDetails) {                    CarInfoVo carInfoVo = new CarInfoVo();                    Long detailId = sOrderDetail.getId();                    String vehicleName = sOrderDetail.getVehicleName();                    SOrderVinExample vinExample = new SOrderVinExample();                    vinExample.createCriteria().andDetailIdEqualTo(detailId);                    SOrderVin sOrderVin = this.getSOrderVinMapper().selectByExample(vinExample).get(0);                    String vin = sOrderVin.getVin();                    carInfoVo.setVehicleName(vehicleName);                    carInfoVo.setVin(vin);                    carInfoVo.setPrice(estValuePrice);                    carInfoVo.setInsurancePrice(price);                    carInfoVos.add(carInfoVo);                }                carInsuranceDetailsVo.setDeliveryDate(deliveryDate);                carInsuranceDetailsVo.setDepartProvinceName(departProvinceName);                carInsuranceDetailsVo.setReceiptProvinceName(receiptProvinceName);                carInsuranceDetailsVo.setDriverName(driverName);                carInsuranceDetailsVo.setDriverPhone(driverPhone);                carInsuranceDetailsVo.setCount(amount);                carInsuranceDetailsVo.setWaybillId(waybillId);                carInsuranceDetailsVo.setCarInfos(carInfoVos);            }            LOGGER.info("select selectCarInsuranceDetails init getSOrders FINISH.");            orders.add(carInsuranceDetailsVo);        } catch (Exception e) {            e.printStackTrace();        }        return orders;    }    /**     * 车保信息列表     */    @Override    public Map<String, Object> selectCarInsuranceDetails(PageVo page) {        LOGGER.info("select selectCarInsuranceDetails init.");        List<CarInsuranceDetailsVo> orders = this.getSOrders();        Map<String, Object> map = new HashMap<String, Object>();        map.put("orders", orders);        map.put("page", page);        return map;    }    /**     * 车保信息导出     */    @Override    public List<String[]> exportCarInsurances(int length) {        LOGGER.info("select selectCarInsuranceDetails export params length : {}.", length);        List<CarInsuranceDetailsVo> sOrders = this.getSOrders();        List<String[]> list = new ArrayList<String[]>();        String str[] = null;        // "出发日期","起运地","目的地","台数","司机姓名","司机电话","运单号","车辆信息"        for (CarInsuranceDetailsVo sOrder : sOrders) {            str = new String[8];            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");            str[0] = sf.format(sOrder.getDeliveryDate());            str[1] = sOrder.getDepartProvinceName();            str[2] = sOrder.getReceiptProvinceName();            str[3] = sOrder.getCount() + "";            str[4] = sOrder.getDriverName();            str[5] = sOrder.getDriverPhone() + "";            str[6] = sOrder.getWaybillId() + "";            List<CarInfoVo> carInfos = sOrder.getCarInfos();            String info = "";            for (CarInfoVo carInfoVo : carInfos) {                BigDecimal price = carInfoVo.getPrice();                BigDecimal insurancePrice = carInfoVo.getInsurancePrice();                String vehicleName = carInfoVo.getVehicleName();                String vin = carInfoVo.getVin();                info += "投保单价：" + price + "，保费：" + insurancePrice + "，车型：" + vehicleName + "，车架号：" + vin + "；" + "\r\n";            }            str[7] = info;            list.add(str);        }        return list;    }    @Override    public Object changeOrderStatus(Long id, int status) {        LOGGER.info("changeOrderStatus update order status params id : {}, status : {}.", id, status);        return this.changeStatus(id, status);    }    @Override    public Collection<ExAndDeInfoVo> getExInfoList(long customerOrderId) {        LOGGER.info("getExInfoList param : {}", customerOrderId);        if (0 == customerOrderId) {            LOGGER.error("getExInfoList customerOrderId must not be 0");            throw new IllegalArgumentException("客户订单id不能是0！");        }        //查询客户订单的所有服务订单 待提车 已提车        //Arrays.asList(SServiceOrderStatusEnum.WAIT_EXTRACT.getValue(),SServiceOrderStatusEnum.HAVE_EXTRACTED.getValue())        List<SServiceOrderVo> sOrders = sServiceOrderService.getListByCOrderId(customerOrderId, null);        if (CollectionUtils.isEmpty(sOrders)) {            return null;        }        sOrders.forEach(order -> order.setStatustext(SServiceOrderStatusEnum.getByValue(order.getStatus()).getText()));        long[] ids = sOrders.stream().mapToLong(order -> order.getId()).toArray();        List<CWaybillDetail> list = cWaybillDetailService.getList(ids, 1, null);        List<ExAndDeInfoVo> result = new ArrayList<>();        Map<Long, List<CWaybillDetail>> map = list.stream().collect(Collectors.groupingBy(CWaybillDetail::getWaybillId));        for (long waybillId : map.keySet()) {            ExAndDeInfoVo vo = new ExAndDeInfoVo();            vo.setWaybillId(waybillId);            List<CWaybillDetail> ds = map.get(waybillId);            List<SServiceOrderVo> findAny = sOrders.stream().filter(order -> this.isHave(order.getId(), ds.stream().mapToLong(detail -> detail.getServiceOrderId()).toArray())).collect(Collectors.toList());            vo.setSorders(findAny);            vo.setStatus(findAny.get(0).getStatus());            vo.setStatusText(findAny.get(0).getStatustext());            vo.setAmount(ds.size());            result.add(vo);        }        return result;    }    @Override    public Collection<ExAndDeInfoVo> getDeInfoList(long customerOrderId) {        LOGGER.info("getDeInfoList param : {}", customerOrderId);        if (0 == customerOrderId) {            LOGGER.error("customerOrderId must not be 0");            throw new IllegalArgumentException("客户订单id不能是0！");        }        //查询客户订单的所有服务订单 已交车 已完成        //Arrays.asList(SServiceOrderStatusEnum.HAVE_DELIVERY.getValue(),SServiceOrderStatusEnum.DONE.getValue())        List<SServiceOrderVo> sOrders = sServiceOrderService.getListByCOrderId(customerOrderId, null);        if (CollectionUtils.isEmpty(sOrders)) {            return null;        }        sOrders.forEach(order -> order.setStatustext(SServiceOrderStatusEnum.getByValue(order.getStatus()).getText()));        long[] ids = sOrders.stream().mapToLong(order -> order.getId()).toArray();        List<CWaybillDetail> list = cWaybillDetailService.getList(ids, 0, true);        List<ExAndDeInfoVo> result = new ArrayList<>();        if (CollectionUtils.isNotEmpty(list)) {            Map<Long, List<CWaybillDetail>> map = list.stream().collect(Collectors.groupingBy(CWaybillDetail::getWaybillId));            for (long waybillId : map.keySet()) {                ExAndDeInfoVo vo = new ExAndDeInfoVo();                vo.setId(customerOrderId);                vo.setWaybillId(waybillId);                List<CWaybillDetail> ds = map.get(waybillId);                List<SServiceOrderVo> findAny = sOrders.stream().filter(order -> this.isHave(order.getId(), ds.stream().mapToLong(detail -> detail.getServiceOrderId()).toArray())).collect(Collectors.toList());                vo.setSorders(findAny);                vo.setStatus(findAny.get(0).getStatus());                vo.setStatusText(findAny.get(0).getStatustext());                vo.setAmount(ds.size());                result.add(vo);            }        }        return result;    }    public boolean isHave(long id, long[] ids) {        for (int i = 0; i < ids.length; i++) {            if (id == ids[i]) {                return true;            }        }        return false;    }    @Override    public Map<String, Object> getCwaybillsByConditions(COrderTrackForm form, PageVo page) throws Exception {        LOGGER.info("getCwaybillsByConditions param : {}", form);        SOrderExample example = new SOrderExample();        example.setLimitStart(page.getStartIndex());        example.setLimitEnd(page.getPageSize());        UserShowVo uservo = userService.getCurrentUser();        Criteria criteria = example.createCriteria();        if (UserTypeEnum.SCOMPANY.getValue() == uservo.getUserType()) {            BCompanyUser companyUser = bCompanyUserService.getCompanyByUserId(uservo.getId());            if (null == companyUser) {                LOGGER.error("getCwaybillsByConditions companyId must not be null");                throw new IllegalArgumentException("查询企业id失败");            }            List<BCompanyUser> bCompanyUsers = null;            if (null != companyUser.getDivisionId()) {                bCompanyUsers = bCompanyUserService.getListByDivisionId(companyUser.getDivisionId());            } else {                bCompanyUsers = bCompanyUserService.getListByCompanyId(companyUser.getCompanyId());            }            if (CollectionUtils.isEmpty(bCompanyUsers)) {                LOGGER.error("getCwaybillsByConditions bCompanyUsers must not be empty");                throw new IllegalArgumentException("查询企业关联用户信息失败");            }            criteria.andUserIdIn(bCompanyUsers.stream().mapToLong(cu -> cu.getUserId()).collect(ArrayList::new, ArrayList::add, ArrayList::addAll));        } else {            criteria.andUserIdEqualTo(uservo.getId());        }        if (CollectionUtils.isNotEmpty(form.getStates())) {            criteria.andStatusIn(form.getStates());        }        if (StringUtils.isNotBlank(form.getOrderCode())) {            criteria.andOrderCodeLike(form.getOrderCode());        }        if (StringUtils.isNotBlank(form.getDepaProvinceCode())) {            criteria.andDepartProvinceCodeEqualTo(form.getDepaProvinceCode());        }        if (StringUtils.isNotBlank(form.getDepaCityCode())) {            criteria.andDepartCityCodeEqualTo(form.getDepaCityCode());        }        if (StringUtils.isNotBlank(form.getDepaCountryCode())) {            criteria.andDepartCountyCodeEqualTo(form.getDepaCountryCode());        }        if (null != form.getDeliveryDate()) {            criteria.andDeliveryDateGreaterThanOrEqualTo(form.getDeliveryDate());        }        if (null != form.getCreateDate()) {            criteria.andCreateTimeGreaterThanOrEqualTo(form.getCreateDate());        }        if (StringUtils.isNotBlank(form.getDestProvinceCode())) {            criteria.andReceiptProvinceCodeEqualTo(form.getDestProvinceCode());        }        if (StringUtils.isNotBlank(form.getDestCityCode())) {            criteria.andReceiptCityCodeEqualTo(form.getDestCityCode());        }        if (StringUtils.isNotBlank(form.getDestCountryCode())) {            criteria.andReceiptCountyCodeEqualTo(form.getDestCountryCode());        }        if (null != form.getArriveDate()) {            criteria.andArriveDateLessThanOrEqualTo(form.getArriveDate());        }        example.setOrderByClause(" update_time desc");        page.setTotalRecord(orderViewMapper.selectByConditionsForPCCount(example));        List<COrderTrackVo> list = orderViewMapper.selectByConditionsForPC(example);        Map<String, Object> m = new HashMap<>();        if (CollectionUtils.isNotEmpty(list)) {            list.forEach(vo -> {                StringBuffer value = new StringBuffer();                vo.getVehicles().forEach(detail -> {                    value.append(detail.getBrandName()).append("-").append(detail.getVehicleName()).append(detail.getAmount()).append("\n\r");                });                vo.setDetail(value.toString());//                  vo.setAmount((int) vo.getVehicles().stream().map(detail -> detail.getAmount()).count());            });            m.put("list", list);            m.put("page", page);            return m;        }        m.put("list", null);        m.put("page", page);        return m;    }    @Override    public void delete(long customerOrderId) {        LOGGER.info("delete param : {}", customerOrderId);        if (0 == customerOrderId) {            LOGGER.error("delete customerOrderId must not be 0");            throw new IllegalArgumentException("客户订单id不能是0");        }        List<Integer> status = new ArrayList<>();        status.add(COrderStatusEnum.SAVED.getValue());        status.add(COrderStatusEnum.CANCELED.getValue());        //删除订单        SOrderExample example = new SOrderExample();        example.createCriteria().andStatusIn(status).andIdEqualTo(customerOrderId);        int result = sOrderMapper.deleteByExample(example);        if (0 == result) {            LOGGER.error("delete failed");            throw new BusinessException("删除失败！");        }        //删除车辆详情        sOrderDetailService.deleteByCOrderId(customerOrderId);        //删除费用详情        sOrderFeeDetailService.deleteByCOrderId(customerOrderId);        //删除车架号        sOrderVinService.deleteByCOrderId(customerOrderId);        //删除状态变更        orderStatusLogService.deleteByCOrderId(customerOrderId);        //删除物流产品        sOrderProductService.deleteByCOrderId(customerOrderId);        //删除服务订单        sServiceOrderService.delete(customerOrderId);    }    @Override    public Map<String, Object> calculateFees(QueryFeesForm feeForm) throws Exception {        LOGGER.info("queryFees params : {}", JSON.toJSON(feeForm));        // 计算运距        BigDecimal distance = mapService.distance(feeForm.getDepaCode(),                new StringBuffer(feeForm.getDepaProvinceName()).append(feeForm.getDepaCityName())                        .append(feeForm.getDepaCountyName()).toString(),                feeForm.getDestCode(), new StringBuffer(feeForm.getDestProvinceName()).append(feeForm.getDestCityName())                        .append(feeForm.getDestCountyName()).toString());        //车辆信息        List<VehiClesInfoFrom> vehicles = JSONArray.parseArray(feeForm.getVehicles(), VehiClesInfoFrom.class);        //判断车型类别是否为空 是则给默认值        vehicles.forEach(vehicle -> {            if (StringUtils.isBlank(vehicle.getType())) {                vehicle.setTypeId(1L);                vehicle.setType(BVehicleConstant.DEFAULT_VEHICLE_CLASS);            }        });        //匹配配置模型        List<Long> vehicleClassIds = vehicles.stream().map(vehicle -> vehicle.getTypeId()).collect(Collectors.toList());        List<Integer> vehicleNum = vehicles.stream().mapToInt(vehicle -> vehicle.getAmount()).collect(ArrayList::new, ArrayList::add, ArrayList::addAll);        BStowageModel stowageModel = bStowageVehicleService.computeSuitableStowage(BStowageModelEnum.ORDER, vehicleClassIds, vehicleNum);        return feesService.queryFees(feeForm.getDepaCode(), feeForm.getDestCode(), distance, stowageModel, feeForm.getProductId(), null, null, vehicles, feeForm.getEstValue(), true, feeForm.getIsPick(), feeForm.getIsDeliv(), true, false);    }    /**     * 获取用户地址到订单     *     * @param soiv     */    private void reSetAddressInOrderByExcel(SOrder order, SOrderImportedVo soiv, boolean isDepart) {        // 发货地址        if (isDepart) {            // order.setDepartAddrId(addressId);            String departProvinceName = soiv.getDepartProvinceName();            String departCityName = soiv.getDepartCityName();            String departAddr = soiv.getDepartAddr();            order.setDepartProvinceCode(soiv.getDepartProvinceCode());            order.setDepartProvinceName(departProvinceName);            order.setDepartCityCode(soiv.getDepartCityCode());            order.setDepartCityName(departCityName);            order.setDepartCountyCode(soiv.getDepartCountyCode());            order.setDepartCountyName(soiv.getDepartCountyName());            order.setDepartUnit(soiv.getDepartUnit());            if (departProvinceName.equals(departCityName)) {                order.setDepartAddr(departCityName + departAddr);            } else {                order.setDepartAddr(departProvinceName + departCityName + departAddr);            }            order.setDepartContact(soiv.getDepartContact());            order.setDepartPhone(soiv.getDepartPhone());            // 收货地址        } else {            // order.setReceiptAddrId(addressId);            String receiptProvinceName = soiv.getReceiptProvinceName();            String receiptCityName = soiv.getReceiptCityName();            String receiptAddr = soiv.getReceiptAddr();            order.setReceiptProvinceCode(soiv.getReceiptProvinceCode());            order.setReceiptProvinceName(receiptProvinceName);            order.setReceiptCityCode(soiv.getReceiptCityCode());            order.setReceiptCityName(receiptCityName);            order.setReceiptCountyCode(soiv.getReceiptCountyCode());            order.setReceiptCountyName(soiv.getReceiptCountyName());            order.setReceiptUnit(soiv.getReceiptUnit());            if (receiptProvinceName.equals(receiptCityName)) {                order.setReceiptAddr(receiptCityName + receiptAddr);            } else {                order.setReceiptAddr(receiptProvinceName + receiptCityName + receiptAddr);            }            order.setReceiptContact(soiv.getReceiptContact());            order.setReceiptPhone(soiv.getReceiptPhone());        }    }    /**     * 获取车辆信息     *     * @param order     * @return     */    private String buildOrderVehicleByExcel(SOrderImportedVo order) {        String vinStr = order.getVins();        String[] vins = vinStr.split(",");        Map<String, Object> brands = new HashMap<String, Object>();        brands.put("vehicleid", order.getVehicleId());        brands.put("vehiclecount", vins.length);        List<Map<String, Object>> vinList = new ArrayList<Map<String, Object>>();        for (String vin : vins) {            Map<String, Object> vinMap = new HashMap<String, Object>();            vinMap.put("vin", vin);            vinMap.put("color", "");            vinList.add(vinMap);        }        brands.put("vins", JSON.toJSONString(vinList));        List<Map<String, Object>> brandList = new ArrayList<Map<String, Object>>();        brandList.add(brands);        return JSON.toJSONString(brandList);    }    @Override    public SOrderVo selectById(long sorderId) {        return sOrderViewMapper.selectByPrimaryKey(sorderId);    }    @SuppressWarnings("unchecked")    @Override    public Collection<BProductCoefficientVo> calculateFees(FeesSearchForm params) throws Exception {        //查询运距        String depaAddr = bAreaService.getFullByCode(params.getDepacode());        String destAddr = bAreaService.getFullByCode(params.getDestcode());        final BigDecimal distance = mapService.distance(params.getDepacode(), depaAddr, params.getDestcode(), destAddr);        //根据车型类型查询车型信息        BVehicleClass vehicleClass = bVehicleClassService.getByVehicleClass(params.getVclass());        if (null == vehicleClass) {            LOGGER.error("calculateFees vclass is incorrect");            throw new IllegalArgumentException("车型类型错误");        }        params.setVclassId(vehicleClass.getId());        //构建车型信息        VehiClesInfoFrom vehicle = new VehiClesInfoFrom();        vehicle.setAmount(1);        vehicle.setTypeId(params.getVclassId());        vehicle.setType(params.getVclass());        //获取符合运距的物流产品信息        List<BProductCoefficientVo> coes = productsService.getCoefficients(distance, false, null, null);        //查询配置模型中整板车辆数        BStowageModel model = bStowageVehicleService.getAvailable(BStowageModelEnum.ORDER);        coes.stream().forEach(vo -> {            //查询运费            Map<String, Object> map = feesService.queryFees(params.getDepacode(), params.getDestcode(), distance, null, null, params.getAdate(), params.getAtime(), Arrays.asList(vehicle), params.getEstValue(), true, params.getIsPick(), params.getIsDeliv(), true, false);            vo.setActivity((BActivityVo) map.get("activity"));            vo.setUnitPrice((BigDecimal) map.get("total"));            //计算打折后费用            vo.setDisUnitPrice((BigDecimal) map.get("actualtotal"));            vo.setFees((List<SOrderFeeDetailVo>) map.get("fees"));            //计算整车价格            vo.setEntirePrice(vo.getUnitPrice().multiply(model.getDiscount()).setScale(0, RoundingMode.UP).setScale(2));            vo.setDisEntirePrice(vo.getDisUnitPrice().multiply(model.getDiscount()).setScale(0, RoundingMode.UP).setScale(2));            vo.setDistance(distance.setScale(2, RoundingMode.UP));        });        return coes;    }    @Override    public Map<String, Object> getListByStatuss(PageVo page, List<Integer> costatus, List<Integer> sostatus) throws Exception {        LOGGER.info("getListByStatuss params : {}, {}, {}", page, costatus, sostatus);        Map<String, Object> map = new HashMap<String, Object>();        SOrderExample example = new SOrderExample();        example.setLimitStart(page.getStartIndex());        example.setLimitEnd(page.getPageSize());        example.setOrderByClause(" update_time desc");        Criteria criteria = example.createCriteria();        //当前用户id        UserShowVo userVo = userService.getCurrentUser();        if (UserTypeEnum.SCOMPANY.getValue() == userVo.getUserType()) {            Long companyId;            BCompanyUser companyUser = bCompanyUserService.getCompanyByUserId(userVo.getId());            if (null == companyUser) {                LOGGER.error("getCwaybillsByConditions companyId must not be null");                throw new IllegalArgumentException("查询企业id失败");            }            List<BCompanyUser> bCompanyUsers = null;            if (null != companyUser.getDivisionId()) {                bCompanyUsers = bCompanyUserService.getListByDivisionId(companyUser.getDivisionId());            } else {                bCompanyUsers = bCompanyUserService.getListByCompanyId(companyUser.getCompanyId());            }            if (null == bCompanyUsers) {                LOGGER.error("getCwaybillsByConditions bCompanyUsers must not be empty");                throw new IllegalArgumentException("查询企业关联用户信息失败");            }            criteria.andUserIdIn(bCompanyUsers.stream().mapToLong(cu -> cu.getUserId()).collect(ArrayList::new, ArrayList::add, ArrayList::addAll));        } else {            criteria.andUserIdEqualTo(userVo.getId());        }        if (CollectionUtils.isNotEmpty(costatus)) {            criteria.andStatusIn(costatus);        }        page.setTotalRecord(orderViewMapper.selectByConditionsForMobileCount(example));        List<OrderVo> orders = orderViewMapper.selectByConditionsForMobile(example);        List<OrderVo> removeOrders = new ArrayList<>();        for (int i = 0; i < orders.size(); i++) {            OrderVo oe = orders.get(i);            oe.setStatusText(COrderStatusEnum.getByValue(oe.getStatus()).getText());            if (null != oe.getPayStatus()) {                oe.setPayStatusText(PaymentStatusEnum.getByValue(oe.getPayStatus()).getText());            }            //拼接省市或市区            if (oe.getIsVeneer()) {                oe.setOrgin(oe.getDepartCityName() + CONTACT_SYMBOL + oe.getDepartCountyName());                oe.setDest(oe.getReceiptCityName() + CONTACT_SYMBOL + oe.getReceiptCountyName());            } else {                oe.setOrgin(oe.getDepartCityName());                oe.setDest(oe.getReceiptCityName());            }            if (CollectionUtils.isNotEmpty(sostatus)) {                List<SOrderDetailVo> svehicles = sServiceOrderVehicleService.getListByCOrderId(oe.getId(), null, sostatus);                if (CollectionUtils.isNotEmpty(svehicles)) {                    oe.setSvehicles(svehicles);                } else {                    removeOrders.add(oe);                    continue;                }            }            // 车型信息            List<COrderDetailVo> vehicles = oe.getVehicles();            oe.setVehicles(null);            if (CollectionUtils.isNotEmpty(vehicles)) {                int count = vehicles.stream().mapToInt(vehicle -> vehicle.getAmount()).sum();                oe.setDetail(                        new StringBuffer().append(vehicles.size()).append("个品牌").append("  " + count).append("辆车").toString());            }        }        orders.removeAll(removeOrders);        map.put("orders", orders);        map.put("page", page);        return map;    }    @Override    public Map<String, Object> getSavedList(PageVo page) throws Exception {        return this.getListByStatuss(page, Arrays.asList(COrderStatusEnum.SAVED.getValue()), null);    }    @Override    public Map<String, Object> getWaitingReceiveList(PageVo page) throws Exception {        return this.getListByStatuss(page, Arrays.asList(COrderStatusEnum.WAIT_RECEIVE.getValue()), null);//      LOGGER.info("SalesOrderServiceImpl.getPendingPaymentList param : {}", page.toString());//      Map<String, Object> map = new HashMap<String, Object>();////      SOrderExample search = new SOrderExample();//      search.setLimitStart(page.getStartIndex());//      search.setLimitEnd(page.getPageSize());//      if (StringUtils.isNotBlank(page.getOrder())) {//          search.setOrderByClause(page.getOrder());//      } else {//          search.setOrderByClause(" update_time DESC");//      }//      long userId = userService.getCurrentUserVo().getId();////      //id 订单类型 待接单//      search.createCriteria().andUserIdEqualTo(userId).andStatusEqualTo(COrderStatusEnum.WAIT_RECEIVE.getValue());////      page.setTotalRecord(sOrderMapper.countByExample(search));//      List<OrderVo> orders = orderViewMapper.selectByPendingPay(search);//      for (int i = 0; i < orders.size(); i++) {//          OrderVo oe = orders.get(i);//          oe.setStatusText(COrderStatusEnum.getByValue(oe.getStatus()).getText());//          oe.setPayStatusText(PaymentStatusEnum.getByValue(oe.getPayStatus()).getText());////          //服务订单车辆信息//          List<SOrderDetailVo> sVehicles = sServiceOrderVehicleService.getListByCOrderId(oe.getId(), null, null);//          oe.setSvehicles(sVehicles);////          // 车型信息//          List<COrderDetailVo> vehicles = oe.getVehicles();//          oe.setVehicles(null);//          if (CollectionUtils.isNotEmpty(vehicles)) {//              int count = vehicles.stream().mapToInt(vehicle -> vehicle.getAmount()).sum();//              oe.setDetail(//                      new StringBuffer().append(vehicles.size()).append("个品牌").append("  "+count).append("辆车").toString());//          }//      }////      map.put("orders", orders);//      map.put("page", page);//      return map;    }    @Override    public Map<String, Object> getPublishedList(PageVo page) throws Exception {        LOGGER.info("SalesOrderServiceImpl.getPublishedList param : {}", page);        Map<String, Object> map = new HashMap<String, Object>();        SOrderExample search = new SOrderExample();        search.setLimitStart(page.getStartIndex());        search.setLimitEnd(page.getPageSize());        if (StringUtils.isNotBlank(page.getOrder())) {            search.setOrderByClause(page.getOrder());        } else {            search.setOrderByClause(" update_time DESC");        }        search.createCriteria().andStatusEqualTo(COrderStatusEnum.WAIT_RECEIVE.getValue())                .andUserIdEqualTo(userService.getCurrentUserVo().getId());        page.setTotalRecord(sOrderMapper.countByExample(search));        List<OrderVo> orders = orderViewMapper.selectByPublished(search);        List<String> ids = new ArrayList<String>();        if (CollectionUtils.isNotEmpty(orders)) {            for (int i = 0; i < orders.size(); i++) {                OrderVo oe = orders.get(i);                ids.add(oe.getId().toString());                oe.setStatusText(COrderStatusEnum.getByValue(oe.getStatus()).getText());                oe.setPayStatusText(PaymentStatusEnum.getByValue(oe.getPayStatus()).getText());                // 车辆信息                List<COrderDetailVo> vehicles = oe.getVehicles();                oe.setVehicles(null);                if (CollectionUtils.isNotEmpty(vehicles)) {                    int count = vehicles.stream().mapToInt(vehicle -> vehicle.getAmount()).sum();                    oe.setDetail(                            new StringBuffer().append(vehicles.size()).append("个品牌").append("  " + count).append("辆车").toString());                }            }        }        // 查询发布剩余时间        // orders = checkPostTimeRemaining(orders, ids);        map.put("orders", orders);        map.put("page", page);        return map;    }    @Override    public Map<String, Object> getPendingPaymentList(PageVo page) throws Exception {        LOGGER.info("SalesOrderServiceImpl.getPendingPaymentList param : {}", page);        Map<String, Object> map = new HashMap<String, Object>();        SOrderExample search = new SOrderExample();        search.setLimitStart(page.getStartIndex());        search.setLimitEnd(page.getPageSize());        if (StringUtils.isNotBlank(page.getOrder())) {            search.setOrderByClause(page.getOrder());        } else {            search.setOrderByClause(" update_time DESC");        }        long userId = userService.getCurrentUserVo().getId();        //id 订单类型 待支付 未付款        search.createCriteria().andUserIdEqualTo(userId).andStatusEqualTo(COrderStatusEnum.SAVED.getValue());        page.setTotalRecord(sOrderMapper.countByExample(search));        List<OrderVo> orders = orderViewMapper.selectByPendingPay(search);        for (int i = 0; i < orders.size(); i++) {            OrderVo oe = orders.get(i);            oe.setStatusText(COrderStatusEnum.getByValue(oe.getStatus()).getText());            oe.setPayStatusText(PaymentStatusEnum.getByValue(oe.getPayStatus()).getText());            //服务订单车辆信息            List<SOrderDetailVo> sVehicles = sServiceOrderVehicleService.getListByCOrderId(oe.getId(), null, null);            oe.setSvehicles(sVehicles);            // 车型信息            List<COrderDetailVo> vehicles = oe.getVehicles();            oe.setVehicles(null);            if (CollectionUtils.isNotEmpty(vehicles)) {                int count = vehicles.stream().mapToInt(vehicle -> vehicle.getAmount()).sum();                oe.setDetail(                        new StringBuffer().append(vehicles.size()).append("个品牌").append("  " + count).append("辆车").toString());            }        }        map.put("orders", orders);        map.put("page", page);        return map;    }    @Override    public Map<String, Object> getInTransitList(PageVo page) throws Exception {        return this.getListByStatuss(page, Arrays.asList(COrderStatusEnum.IN_TRANSIT.getValue()), Arrays.asList(SServiceOrderStatusEnum.WAIT_DISPATCH.getValue(),                SServiceOrderStatusEnum.WAIT_EXTRACT.getValue(),                SServiceOrderStatusEnum.HAVE_EXTRACTED.getValue(),                SServiceOrderStatusEnum.HAVE_ISSUSD.getValue(),                SServiceOrderStatusEnum.HAVE_DELIVERY.getValue()));//      LOGGER.info("SalesOrderServiceImpl.getPendingPaymentList param : {}", page.toString());//      Map<String, Object> map = new HashMap<String, Object>();//      SOrderExample search = new SOrderExample();//      search.setLimitStart(page.getStartIndex());//      search.setLimitEnd(page.getPageSize());//      if (StringUtils.isNotBlank(page.getOrder())) {//          search.setOrderByClause(page.getOrder());//      } else {//          search.setOrderByClause(" update_time DESC");//      }//      long userId = userService.getCurrentUserVo().getId();////      // 执行中//      search.createCriteria().andUserIdEqualTo(userId).andStatusEqualTo(COrderStatusEnum.IN_TRANSIT.getValue());////      page.setTotalRecord(sOrderMapper.countByExample(search));//      List<OrderVo> orders = orderViewMapper.selectByPendingPay(search);//      List<OrderVo> removeOrders = new ArrayList<>();//      for (int i = 0; i < orders.size(); i++) {//          OrderVo oe = orders.get(i);//          oe.setStatusText(COrderStatusEnum.getByValue(oe.getStatus()).getText());//          oe.setPayStatusText(PaymentStatusEnum.getByValue(oe.getPayStatus()).getText());////          List<SOrderDetailVo> svehicles = sServiceOrderVehicleService.getListByCOrderId(oe.getId(), null,//                  Arrays.asList(SServiceOrderStatusEnum.WAIT_DISPATCH.getValue(),//                          SServiceOrderStatusEnum.WAIT_EXTRACT.getValue(),//                          SServiceOrderStatusEnum.HAVE_EXTRACTED.getValue(),//                          SServiceOrderStatusEnum.HAVE_ISSUSD.getValue(),//                          SServiceOrderStatusEnum.HAVE_DELIVERY.getValue()));//          if(CollectionUtils.isNotEmpty(svehicles)){//              oe.setSvehicles(svehicles);//          }else{//              removeOrders.add(oe);//              continue;//          }////          // 车型信息//          List<COrderDetailVo> vehicles = oe.getVehicles();//          oe.setVehicles(null);//          if (CollectionUtils.isNotEmpty(vehicles)) {//              int count = vehicles.stream().mapToInt(vehicle -> vehicle.getAmount()).sum();//              oe.setDetail(//                      new StringBuffer().append(vehicles.size()).append("个品牌").append("  "+count).append("辆车").toString());//          }//      }//      orders.removeAll(removeOrders);//      map.put("orders", orders);//      map.put("page", page);//      return map;    }    @Override    public Map<String, Object> getCompletedList(PageVo page) throws Exception {        return this.getListByStatuss(page, Arrays.asList(COrderStatusEnum.COMPLETED.getValue()), Arrays.asList(SServiceOrderStatusEnum.HAVE_DELIVERY.getValue()));//      Map<String, Object> map = new HashMap<String, Object>();////      SOrderExample search = new SOrderExample();//      search.setLimitStart(page.getStartIndex());//      search.setLimitEnd(page.getPageSize());//      if (StringUtils.isNotBlank(page.getOrder())) {//          search.setOrderByClause(page.getOrder());//      } else {//          search.setOrderByClause(" update_time DESC");//      }//      long userId = userService.getCurrentUserVo().getId();////      search.createCriteria().andUserIdEqualTo(userId).andStatusEqualTo(COrderStatusEnum.COMPLETED.getValue());////      page.setTotalRecord(sOrderMapper.countByExample(search));//      List<OrderVo> orders = orderViewMapper.selectByPendingPay(search);//      List<OrderVo> removeOrders = new ArrayList<>();//      for (int i = 0; i < orders.size(); i++) {//          OrderVo oe = orders.get(i);//          oe.setStatusText(COrderStatusEnum.getByValue(oe.getStatus()).getText());//          oe.setPayStatusText(PaymentStatusEnum.getByValue(oe.getPayStatus()).getText());////          List<SOrderDetailVo> svehicles = sServiceOrderVehicleService.getListByCOrderId(oe.getId(), null, Arrays.asList(SServiceOrderStatusEnum.HAVE_DELIVERY.getValue()));//          if(CollectionUtils.isNotEmpty(svehicles)){//              oe.setSvehicles(svehicles);//          }else{//              removeOrders.add(oe);//              continue;//          }//          // 车型信息//          List<COrderDetailVo> vehicles = oe.getVehicles();//          oe.setVehicles(null);//          if (CollectionUtils.isNotEmpty(vehicles)) {//              int count = vehicles.stream().mapToInt(vehicle -> vehicle.getAmount()).sum();//              oe.setDetail(//                      new StringBuffer().append(vehicles.size()).append("个品牌").append("  "+count).append("辆车").toString());//          }//      }//      orders.removeAll(removeOrders);//      map.put("orders", orders);//      map.put("page", page);//      return map;    }    @Override    public Map<String, Object> getDoneList(PageVo page) throws Exception {        return this.getListByStatuss(page, Arrays.asList(COrderStatusEnum.DONE.getValue()), null);//      LOGGER.info("SalesOrderServiceImpl.getDoneList params : {}", page.toString());//      Map<String, Object> map = new HashMap<>();//      SOrderExample search = new SOrderExample();//      search.setLimitStart(page.getStartIndex());//      search.setLimitEnd(page.getPageSize());//      if (StringUtils.isNotBlank(page.getOrder())) {//          search.setOrderByClause(page.getOrder());//      } else {//          search.setOrderByClause(" update_time DESC");//      }//      long userId = userService.getCurrentUserVo().getId();////      // 已完成//      search.createCriteria().andUserIdEqualTo(userId).andStatusEqualTo(COrderStatusEnum.DONE.getValue());////      page.setTotalRecord(sOrderMapper.countByExample(search));//      List<OrderVo> orders = orderViewMapper.selectByDone(search);//      for (int i = 0; i < orders.size(); i++) {//          OrderVo oe = orders.get(i);//          oe.setStatusText(COrderStatusEnum.getByValue(oe.getStatus()).getText());//          oe.setPayStatusText(PaymentStatusEnum.getByValue(oe.getPayStatus()).getText());////          // 车型信息//          List<COrderDetailVo> vehicles = oe.getVehicles();//          oe.setVehicles(null);//          if (CollectionUtils.isNotEmpty(vehicles)) {//              int count = vehicles.stream().mapToInt(vehicle -> vehicle.getAmount()).sum();//              oe.setDetail(//                      new StringBuffer().append(vehicles.size()).append("个品牌").append("  "+count).append("辆车").toString());//          }//      }//      map.put("orders", orders);//      map.put("page", page);//      return map;    }    @Override    public Map<String, Object> getAllList(PageVo page) throws Exception {        return this.getListByStatuss(page, null, null);//      Map<String, Object> map = new HashMap<String, Object>();////      SOrderExample search = new SOrderExample();//      search.setLimitStart(page.getStartIndex());//      search.setLimitEnd(page.getPageSize());//      if (StringUtils.isNotBlank(page.getOrder())) {//          search.setOrderByClause(page.getOrder());//      } else {//          search.setOrderByClause(" update_time DESC");//      }//      long userId = userService.getCurrentUserVo().getId();////      search.createCriteria().andUserIdEqualTo(userId);//      page.setTotalRecord(sOrderMapper.countByExample(search));//      List<OrderVo> orders = orderViewMapper.selectByPendingPay(search);//      for (int i = 0; i < orders.size(); i++) {//          OrderVo oe = orders.get(i);//          oe.setStatusText(COrderStatusEnum.getByValue(oe.getStatus()).getText());//          oe.setPayStatusText(PaymentStatusEnum.getByValue(oe.getPayStatus()).getText());////          // 车型信息//          List<COrderDetailVo> vehicles = oe.getVehicles();//          oe.setVehicles(null);//          if (CollectionUtils.isNotEmpty(vehicles)) {//              int count = vehicles.stream().mapToInt(vehicle -> vehicle.getAmount()).sum();//              oe.setDetail(//                      new StringBuffer().append(vehicles.size()).append("个品牌").append("  "+count).append("辆车").toString());//          }//      }////      map.put("orders", orders);//      map.put("page", page);//      return map;    }    /**     * @param id     * @param list     * @return     * @Title: getSurplusTimeByOrder     * @Description: 返回剩余时间 秒     */    public void addUserVehicles(long id, List<VehiclesBrandVo> list) {        BVehicle vehicle = null;        BVehicleBrand vehicleBrand = null;        VehiclesBrandVo brandVo = null;        for (int i = 0; i < list.size(); i++) {            brandVo = list.get(i);            SUserVehicles uv = new SUserVehicles();            uv.setUserId(id);            // 根据id获取车型信息和品牌信息            vehicle = vehicleMapper.selectByPrimaryKey(brandVo.getVehicleid());            if (vehicle == null) {                LOGGER.error("vehicle is null");                throw new BusinessException("获取车型信息失败！");            }            vehicleBrand = brandMapper.selectByPrimaryKey(vehicle.getBrandId());            if (vehicleBrand == null) {                LOGGER.error("vehicleBrand is null");                throw new BusinessException("获取品牌信息失败！");            }            uv.setVehicleId(vehicle.getId());            uv.setVehicleName(vehicle.getVehicleName());            uv.setBrandId(vehicleBrand.getId());            uv.setBrandName(vehicleBrand.getBrandName());            uv.setBrandLogo(vehicleBrand.getBrandLogo());            uv.setSysVehicleClass(vehicle.getSysVehicleClass());            SUserVehiclesExample search = new SUserVehiclesExample();            search.createCriteria().andUserIdEqualTo(id).andVehicleIdEqualTo(list.get(i).getVehicleid());            if (userVehiclesMapper.selectByExample(search).isEmpty()) {                int uvid = userVehiclesMapper.insertSelective(uv);                LOGGER.info("SalesOrderServiceImpl.addUserVehicles insertSelective return : {}", uvid);            }        }    }    @Override    public Map<String, Object> calculateIntracityFees(Long depaId, Long destId, Integer trailerId, Integer vehicleNum, Date deliveryDate, String deliveryTime) throws Exception {        LOGGER.info("calculateIntracityFees params : {}, {}, {}, {}", depaId, destId, trailerId, vehicleNum);        Map<String, Object> map = new HashMap<String, Object>();        //出发地地址        SUserAddr depaAddress = userAddressService.selectUserAddressById(depaId.toString());        //目的地地址        SUserAddr destAddress = userAddressService.selectUserAddressById(destId.toString());        //查询公里数        BigDecimal distance = this.queryIntracityDistanceByUserAddr(depaAddress, destAddress);        map.put("distance", distance.setScale(2, RoundingMode.UP) + "KM");        //计算费用        if (null != trailerId && null != vehicleNum) {            map.putAll(feesService.queryIntracityFees(depaAddress.getCityCode(), distance, vehicleNum, trailerId));        }        //计算到达时间        if (null != distance && null != deliveryDate && StringUtils.isNotBlank(deliveryTime)) {            DateTime arrival = this.calculateArrivalTime(distance, deliveryDate, deliveryTime);            map.put("arrivalDate", arrival.toString("yyyy-MM-dd"));            map.put("arrivalTime", arrival.toString("HH:mm"));        }        return map;    }    private BigDecimal queryIntracityDistanceByUserAddr(SUserAddr depaAddress, SUserAddr destAddress) {        String depaLongitudeAndLatitude = depaAddress.getLongitude() + "," + depaAddress.getLatitude();        String destLongitudeAndLatitude = destAddress.getLongitude() + "," + destAddress.getLatitude();        BigDecimal distance = bDistanceBetweenAddressesService.getDistanceByLongitudeAndLatitude(depaLongitudeAndLatitude, destLongitudeAndLatitude);        //计算公里数        if (null == distance) {            distance = mapService.getDistanceByLongitudeAndLatitude(depaLongitudeAndLatitude, destLongitudeAndLatitude);            //保存两地址间距离            BDistanceBetweenAddresses addresses = new BDistanceBetweenAddresses();            addresses.setDepaProvinceName(depaAddress.getProvinceName());            addresses.setDepaProvinceCode(depaAddress.getProvinceCode());            addresses.setDepaCityName(depaAddress.getCityName());            addresses.setDepaCityCode(depaAddress.getCityCode());            addresses.setDepaCountyName(depaAddress.getCountyName());            addresses.setDepaCountyCode(depaAddress.getCountyCode());            addresses.setDepaAddress(depaAddress.getDetailAddress());            addresses.setDepaTitle(depaAddress.getAddress());            addresses.setDepaLongitude(depaAddress.getLongitude());            addresses.setDepaLatitude(depaAddress.getLatitude());            addresses.setDestProvinceName(destAddress.getProvinceName());            addresses.setDestProvinceCode(destAddress.getProvinceCode());            addresses.setDestCityName(destAddress.getCityName());            addresses.setDestCityCode(destAddress.getCityCode());            addresses.setDestCountyName(destAddress.getCountyName());            addresses.setDestCountyCode(destAddress.getCountyCode());            addresses.setDestAddress(destAddress.getDetailAddress());            addresses.setDestTitle(destAddress.getAddress());            addresses.setDestLongitude(destAddress.getLongitude());            addresses.setDestLatitude(destAddress.getLatitude());            addresses.setDistance(distance);            bDistanceBetweenAddressesService.add(addresses);        }        return distance;    }    private DateTime calculateArrivalTime(BigDecimal distance, Date deliveryDate, String deliveryTime) {        LOGGER.info("calculateArrivalTime params : {}, {}, {}", distance, deliveryDate, deliveryTime);        if (null == distance) {            LOGGER.error("calculateArrivalTime param distance must not be null");            throw new IllegalArgumentException("运距不能为空");        }        if (null == deliveryDate) {            LOGGER.error("calculateArrivalTime param deliveryDate must not be null");            throw new IllegalArgumentException("到达日期不能为空");        }        if (StringUtils.isBlank(deliveryTime)) {            LOGGER.error("calculateArrivalTime param deliveryTime must not be null");            throw new IllegalArgumentException("到达时间不能为空");        }        //计算同城到达时间        if (distance.compareTo(BigDecimal.ZERO) == 1) {            Calendar cal = Calendar.getInstance();            cal.setTime(deliveryDate);            ;            cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(deliveryTime.substring(0, 2)));            cal.set(Calendar.MINUTE, Integer.parseInt(deliveryTime.substring(3, 5)));            DateTime dDime = new DateTime(cal.get(cal.YEAR), cal.get(cal.MONTH) + 1, cal.get(cal.DATE), cal.get(cal.HOUR_OF_DAY), cal.get(cal.MINUTE));            return dDime.plusHours(distance.divide(BigDecimal.valueOf(40), 0, RoundingMode.UP).intValue() + 1);        }        return null;    }    @Override    public void addIntracityOrder(IntracityOrderForm form) throws Exception {        LOGGER.info("addIntracityOrder.create params : {}", form);        SOrder order = new SOrder();        UserVo userVo = userService.getCurrentUserVo();        Integer userType = userService.getCurrentUserVo().getType();        order.setUserId(userVo.getId());        order.setOrderCode(UniquenessFlagUnits.generateUniquenessFlag("CO"));        order.setDeliveryDate(form.getDeliveryDate());        order.setDeliveryTime(form.getDeliveryTime());        order.setArriveDate(form.getArriveDate());        order.setArriveTime(form.getArriveTime());        order.setOrderType(userType);        order.setIsVeneer(form.getIsVeneer());        order.setAmount(form.getVehicleNum());        order.setComment(form.getComment());        order.setIsUrgent(form.getIsUrgent());        order.setTransportType(form.getTransportType());        order.setIsTicket(form.getTicket());        order.setIsAppoint(form.getAppoint());        // 地址赋值        this.reSetAddressInOrder(order, form.getDepaId(), userVo.getId(), AddressTypeEnum.SHIP.getValue());        this.reSetAddressInOrder(order, form.getDestId(), userVo.getId(), AddressTypeEnum.RECEIPT.getValue());        // 保存状态、未付款状态        order.setStatus(COrderStatusEnum.WAIT_RECEIVE.getValue());        order.setPayStatus(PaymentStatusEnum.UNPAID.getValue());        // 计算运距        SUserAddr depa = userAddressMapper.selectByPrimaryKey(form.getDepaId());        SUserAddr rece = userAddressMapper.selectByPrimaryKey(form.getDestId());        order.setDistance(this.queryIntracityDistanceByUserAddr(depa, rece));        // 保存订单        sOrderMapper.insertSelective(order);        //保存订单和板车关联信息        sOrderTrailerService.add(form.getTrailerId(), order.getId());        // 保存订单流转状态变更        orderStatusLogService.insertSelective(order.getId(), StatusCategoryEnum.PROCESS, COrderStatusEnum.WAIT_RECEIVE, false, null);        // 保存订单车辆信息        List<VehiclesBrandVo> vehiclesBrandList = JSONArray.parseArray(form.getVehicles(), VehiclesBrandVo.class);        this.buildVehicles(vehiclesBrandList, order.getId(), null);        // 保存用户常用车辆        this.addUserVehicles(userVo.getId(), vehiclesBrandList);        // 计算订单费用        Map<String, Object> map = feesService.queryIntracityFees(order.getReceiptCityCode(), order.getDistance(), form.getVehicleNum(), form.getTrailerId());//      Map<String, Object> map = this.calculateIntracityFees(form.getDepaId(), form.getDestId(), form.getTrailerId(), form.getVehicleNum());        order.setOrderCost((BigDecimal) map.get("total"));        order.setActualCost((BigDecimal) map.get("actualTotal"));        //保存费用详情        List<SOrderFeeDetailVo> fees = (List<SOrderFeeDetailVo>) map.get("fees");        if (CollectionUtils.isNotEmpty(fees)) {            fees.forEach(fee -> sOrderFeeDetailService.addFeeDetail(order.getId(), fee.getId(), fee.getFeeCode(), fee.getFeeName(), fee.getCost(), fee.getActualAmount()));        }        this.updateOrderByPrimaryKeySelective(order);        //生成服务订单        this.buildServiceOrder(order, null);        // 生成 订单和支付角色的关系        Result<String> result = this.getSOrderPayRoleService().addSorderPayRoleRelations(order.getId(), userVo.getId(), form.getPayRole(), form.getPhone());        this.sendMessageDispatch(order);        if (!result.isSuccess()) {            throw new BusinessException(result.getMessage());        }    }    @Override    public void updateOrderByPrimaryKeySelective(SOrder order) {        sOrderMapper.updateByPrimaryKeySelective(order);    }    @Override    public OrderTrailVo getOrderTrailByOrderId(long customerOrderId) throws Exception {        LOGGER.info("getOrderTrailByOrderId param : {}", customerOrderId);        if (Objects.equals(customerOrderId, 0) || Objects.equals(customerOrderId, null)) {            LOGGER.error("getOrderTrailByOrderId customerOrderId must not be 0");            throw new IllegalArgumentException("客户订单id不能是0！");        }        Map<String, Object> paramsMap = new HashMap<>();        Long userId = userService.getCurrentUserVo().getId();        paramsMap.put("customerOrderId", customerOrderId);        BCompanyUser companyUser = bCompanyUserService.getCompanyByUserId(userId);        List<BCompanyUser> bCompanyUsers = null;        if (!Objects.equals(companyUser.getDivisionId(), null)) {            bCompanyUsers = bCompanyUserService.getListByDivisionId(companyUser.getDivisionId());        } else {            bCompanyUsers = bCompanyUserService.getListByCompanyId(companyUser.getCompanyId());        }        List<Long> userList = bCompanyUsers.stream().map(item -> item.getUserId()).collect(Collectors.toList());        paramsMap.put("userList", userList);        OrderTrailVo vo = orderViewMapper.selectOrderListByCondition(paramsMap);        if (!Objects.equals(vo, null)) {            if (vo.getVeneer()) {                vo.setOrgin(vo.getDepartCityName() + CONTACT_SYMBOL + vo.getDepartCountyName());                vo.setDest(vo.getReceiptCityName() + CONTACT_SYMBOL + vo.getReceiptCountyName());            } else {                vo.setOrgin(vo.getDepartCityName());                vo.setDest(vo.getReceiptCityName());            }            List<ServiceOrderLogisticsVo> sorders = vo.getSorders();            if (CollectionUtils.isNotEmpty(sorders)) {                sorders.forEach(order -> {                    order.setStatustext(SServiceOrderStatusEnum.getByValue(order.getStatus()).getText());                    // 通过服务订单号找运单号                    CWaybillDetailExample example = new CWaybillDetailExample();                    example.createCriteria().andServiceOrderIdEqualTo(order.getId());                    List<CWaybillDetail> details = cWaybillDetailMapper.selectByExample(example);                    if (CollectionUtils.isNotEmpty(details)) {                        // 提车时间                        List<CWaybillAttach> receiptList = cWaybillAttachService.getByWaybillid(details.get(0).getWaybillId(), AttachCategoryEnumWaybill.RECEIPT.getValue(), null);                        if (CollectionUtils.isNotEmpty(receiptList)) {                            order.setDeliveryDate(receiptList.get(0).getCreatTime());                        }                        // 交车时间                        List<CWaybillAttach> deliverList = cWaybillAttachService.getByWaybillid(details.get(details.size() - 1).getWaybillId(), AttachCategoryEnumWaybill.DELIVER.getValue(), null);                        if (CollectionUtils.isNotEmpty(deliverList)) {                            order.setArriveDate(deliverList.get(0).getCreatTime());                        }                        // 提车人                        List<CWaybillContacts> contactss = cWaybillContactsService.selectContacts(details.get(0).getWaybillId(), WaybillContactsTypeEnum.DEPARTPERSON.getValue());                        if (CollectionUtils.isNotEmpty(contactss)) {                            order.setDeliveryName(contactss.get(0).getContact());                        }                        // 在途位置 在途时间                        List<CWaybillTrail> trails = cWaybillTrailService.selectByWaybillId(details.get(details.size() - 1).getWaybillId());                        if (CollectionUtils.isNotEmpty(trails)) {                            CWaybillTrail trail = trails.get(trails.size() - 1);                            order.setLocation(trail.getCityName());                            order.setOnOrderDate(trail.getUpdateTime());                        }                        order.setDeliveryWaybillId(details.get(0).getWaybillId());                        order.setArriveWaybillId(details.get(details.size() - 1).getWaybillId());                    }                });            }            return vo;        }        return null;    }}